3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.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"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
35 #include "InsetIterator.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
44 #include "TextClass.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
96 using std::istringstream;
100 using std::mem_fun_ref;
104 namespace Alert = frontend::Alert;
108 /// Return an inset of this class if it exists at the current cursor position
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
113 DocIterator it = cur;
114 if (it.nextInset() &&
115 it.nextInset()->lyxCode() == code) {
116 inset = static_cast<T*>(it.nextInset());
124 BufferView::BufferView()
125 : width_(0), height_(0), buffer_(0), wh_(0),
127 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 intl_(new Intl), last_inset_(0)
130 xsel_cache_.set = false;
131 intl_->initKeyMapper(lyxrc.use_kbmap);
135 BufferView::~BufferView()
140 Buffer * BufferView::buffer() const
146 void BufferView::setBuffer(Buffer * b)
148 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149 << "[ b = " << b << "]" << endl;
152 // Save the actual cursor position and anchor inside the
153 // buffer so that it can be restored in case we rechange
154 // to this buffer later on.
155 buffer_->saveCursor(cursor_.selectionBegin(),
156 cursor_.selectionEnd());
157 // update bookmark pit of the current buffer before switch
158 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159 BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160 if (buffer()->fileName() != bm.filename.absFilename())
162 // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
167 boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
171 // current buffer is going to be switched-off, save cursor pos
172 // Ideally, the whole cursor stack should be saved, but session
173 // currently can only handle bottom (whole document) level pit and pos.
174 // That is to say, if a cursor is in a nested inset, it will be
175 // restore to the left of the top level inset.
176 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
180 // If we're quitting lyx, don't bother updating stuff
186 //FIXME Fix for bug 3440 is here.
187 // If we are closing current buffer, switch to the first in
190 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
191 << " No Buffer!" << endl;
192 // We are closing the buffer, use the first buffer as current
194 // if (last_buffer_) buffer_ = last_buffer_;
195 // also check that this is in theBufferList()?
196 buffer_ = theBufferList().first();
199 // last_buffer = buffer_;
200 // Set current buffer
205 cursor_ = Cursor(*this);
212 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
213 << "Buffer addr: " << buffer_ << endl;
214 cursor_.push(buffer_->inset());
215 cursor_.resetAnchor();
216 buffer_->text().setCurrentFont(cursor_);
217 if (buffer_->getCursor().size() > 0 &&
218 buffer_->getAnchor().size() > 0)
220 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
221 cursor_.resetAnchor();
222 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
223 cursor_.setSelection();
224 // do not set selection to the new buffer because we
225 // only paste recent selection.
227 // Make sure that the restored cursor is not broken. This can happen for
228 // example if this Buffer has been modified by another view.
229 cursor_.fixIfBroken();
231 updateMetrics(false);
232 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
233 graphics::Previews::get().generateBufferPreviews(*buffer_);
237 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
239 // File already open?
240 if (theBufferList().exists(filename.absFilename())) {
241 docstring const file = makeDisplayPath(filename.absFilename(), 20);
242 docstring text = bformat(_("The document %1$s is already "
243 "loaded.\n\nDo you want to revert "
244 "to the saved version?"), file);
245 int const ret = Alert::prompt(_("Revert to saved document?"),
246 text, 0, 1, _("&Revert"), _("&Switch to document"));
249 setBuffer(theBufferList().getBuffer(filename.absFilename()));
252 // FIXME: should be LFUN_REVERT
253 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
255 // Fall through to new load. (Asger)
261 if (isFileReadable(filename)) {
262 b = theBufferList().newBuffer(filename.absFilename());
263 if (!lyx::loadLyXFile(b, filename)) {
264 theBufferList().release(b);
268 docstring text = bformat(_("The document %1$s does not yet "
269 "exist.\n\nDo you want to create "
270 "a new document?"), from_utf8(filename.absFilename()));
271 int const ret = Alert::prompt(_("Create new document?"),
272 text, 0, 1, _("&Create"), _("Cancel"));
275 b = newFile(filename.absFilename(), string(), true);
283 // Send the "errors" signal in case of parsing errors
286 // Update the labels and section numbering.
287 updateLabels(*buffer_);
288 // scroll to the position when the file was last closed
289 if (lyxrc.use_lastfilepos) {
292 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
293 // if successfully move to pit (returned par_id is not zero), update metrics and reset font
294 if (moveToPosition(pit, pos, 0, 0).get<1>()) {
296 updateMetrics(false);
297 buffer_->text().setCurrentFont(cursor_);
302 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
308 void BufferView::resize()
313 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
315 updateMetrics(false);
320 bool BufferView::fitCursor()
322 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
323 frontend::FontMetrics const & fm =
324 theFontMetrics(cursor_.getFont());
325 int const asc = fm.maxAscent();
326 int const des = fm.maxDescent();
327 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
328 if (p.y_ - asc >= 0 && p.y_ + des < height_)
336 bool BufferView::multiParSel()
338 if (!cursor_.selection())
340 bool ret = multiparsel_cache_;
341 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
342 // Either this, or previous selection spans paragraphs
343 return ret || multiparsel_cache_;
347 bool BufferView::update(Update::flags flags)
349 // last_inset_ points to the last visited inset. This pointer may become
350 // invalid because of keyboard editing. Since all such operations
351 // causes screen update(), I reset last_inset_ to avoid such a problem.
353 // This is close to a hot-path.
355 << BOOST_CURRENT_FUNCTION
356 << "[fitcursor = " << (flags & Update::FitCursor)
357 << ", forceupdate = " << (flags & Update::Force)
358 << ", singlepar = " << (flags & Update::SinglePar)
359 << "] buffer: " << buffer_ << endl;
361 // Check needed to survive LyX startup
365 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
367 // Update macro store
368 if (!(cursor().inMathed() && cursor().inMacroMode()))
369 buffer_->buildMacros();
371 // Now do the first drawing step if needed. This consists on updating
372 // the CoordCache in updateMetrics().
373 // The second drawing step is done in WorkArea::redraw() if needed.
375 // Case when no explicit update is requested.
377 // no need to redraw anything.
378 metrics_info_.update_strategy = NoScreenUpdate;
382 if (flags == Update::Decoration) {
383 metrics_info_.update_strategy = DecorationUpdate;
387 if (flags == Update::FitCursor
388 || flags == (Update::Decoration | Update::FitCursor)) {
389 bool const fit_cursor = fitCursor();
390 // tell the frontend to update the screen if needed.
392 updateMetrics(false);
395 if (flags & Update::Decoration) {
396 metrics_info_.update_strategy = DecorationUpdate;
399 // no screen update is needed.
400 metrics_info_.update_strategy = NoScreenUpdate;
404 bool full_metrics = flags & Update::Force;
405 if (flags & Update::MultiParSel)
406 full_metrics |= multiParSel();
408 bool const single_par = !full_metrics;
409 updateMetrics(single_par);
411 if (flags & Update::FitCursor && fitCursor())
412 updateMetrics(false);
414 // tell the frontend to update the screen.
419 void BufferView::updateScrollbar()
422 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
423 << " no text in updateScrollbar" << endl;
424 scrollbarParameters_.reset();
428 Text & t = buffer_->text();
429 TextMetrics & tm = text_metrics_[&t];
431 int const parsize = int(t.paragraphs().size() - 1);
432 if (anchor_ref_ > parsize) {
433 anchor_ref_ = parsize;
438 << BOOST_CURRENT_FUNCTION
439 << " Updating scrollbar: height: " << t.paragraphs().size()
440 << " curr par: " << cursor_.bottom().pit()
441 << " default height " << defaultRowHeight() << endl;
443 // It would be better to fix the scrollbar to understand
444 // values in [0..1] and divide everything by wh
446 // estimated average paragraph height:
450 int h = tm.parMetrics(anchor_ref_).height();
452 // Normalize anchor/offset (MV):
453 while (offset_ref_ > h && anchor_ref_ < parsize) {
456 h = tm.parMetrics(anchor_ref_).height();
458 // Look at paragraph heights on-screen
461 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
464 int const h2 = tm.parMetrics(pit).height();
470 int const hav = sumh / nh;
471 // More realistic average paragraph height
476 scrollbarParameters_.height = (parsize + 1) * wh_;
477 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
478 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
482 ScrollbarParameters const & BufferView::scrollbarParameters() const
484 return scrollbarParameters_;
488 void BufferView::scrollDocView(int value)
490 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
491 << "[ value = " << value << "]" << endl;
496 Text & t = buffer_->text();
497 TextMetrics & tm = text_metrics_[&t];
499 float const bar = value / float(wh_ * t.paragraphs().size());
501 anchor_ref_ = int(bar * t.paragraphs().size());
502 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
503 anchor_ref_ = int(t.paragraphs().size()) - 1;
505 tm.redoParagraph(anchor_ref_);
506 int const h = tm.parMetrics(anchor_ref_).height();
507 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
508 updateMetrics(false);
512 void BufferView::setCursorFromScrollbar()
517 Text & t = buffer_->text();
519 int const height = 2 * defaultRowHeight();
520 int const first = height;
521 int const last = height_ - height;
522 Cursor & cur = cursor_;
524 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
527 case bv_funcs::CUR_ABOVE:
528 // We reset the cursor because bv_funcs::status() does not
529 // work when the cursor is within mathed.
530 cur.reset(buffer_->inset());
531 t.setCursorFromCoordinates(cur, 0, first);
532 cur.clearSelection();
534 case bv_funcs::CUR_BELOW:
535 // We reset the cursor because bv_funcs::status() does not
536 // work when the cursor is within mathed.
537 cur.reset(buffer_->inset());
538 t.setCursorFromCoordinates(cur, 0, last);
539 cur.clearSelection();
541 case bv_funcs::CUR_INSIDE:
542 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
543 int const newy = min(last, max(y, first));
545 cur.reset(buffer_->inset());
546 t.setCursorFromCoordinates(cur, 0, newy);
552 Change const BufferView::getCurrentChange() const
554 if (!cursor_.selection())
555 return Change(Change::UNCHANGED);
557 DocIterator dit = cursor_.selectionBegin();
558 return dit.paragraph().lookupChange(dit.pos());
562 void BufferView::saveBookmark(unsigned int idx)
564 // tenatively save bookmark, id and pos will be used to
565 // acturately locate a bookmark in a 'live' lyx session.
566 // pit and pos will be updated with bottom level pit/pos
568 LyX::ref().session().bookmarks().save(
569 FileName(buffer_->fileName()),
570 cursor_.bottom().pit(),
571 cursor_.bottom().pos(),
572 cursor_.paragraph().id(),
577 // emit message signal.
578 message(_("Save bookmark"));
582 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
583 int top_id, pos_type top_pos)
585 cursor_.clearSelection();
587 // if a valid par_id is given, try it first
588 // This is the case for a 'live' bookmark when unique paragraph ID
589 // is used to track bookmarks.
591 ParIterator par = buffer_->getParFromID(top_id);
592 if (par != buffer_->par_iterator_end()) {
593 DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
594 // Some slices of the iterator may not be
595 // reachable (e.g. closed collapsable inset)
596 // so the dociterator may need to be
597 // shortened. Otherwise, setCursor may crash
598 // lyx when the cursor can not be set to these
600 size_t const n = dit.depth();
601 for (size_t i = 0; i < n; ++i)
602 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
607 // Note: return bottom (document) level pit.
608 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
611 // if top_id == 0, or searching through top_id failed
612 // This is the case for a 'restored' bookmark when only bottom
613 // (document level) pit was saved. Because of this, bookmark
614 // restoration is inaccurate. If a bookmark was within an inset,
615 // it will be restored to the left of the outmost inset that contains
617 if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
618 DocIterator it = doc_iterator_begin(buffer_->inset());
619 it.pit() = bottom_pit;
620 it.pos() = min(bottom_pos, it.paragraph().size());
622 return boost::make_tuple(it.pit(), it.pos(),
623 it.paragraph().id());
626 return boost::make_tuple(pit_type(0), pos_type(0), 0);
630 void BufferView::switchKeyMap()
632 if (!lyxrc.rtl_support)
635 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
636 if (intl_->keymap == Intl::PRIMARY)
639 if (intl_->keymap == Intl::SECONDARY)
645 int BufferView::workWidth() const
651 void BufferView::center()
653 CursorSlice & bot = cursor_.bottom();
654 TextMetrics & tm = text_metrics_[bot.text()];
655 pit_type const pit = bot.pit();
656 tm.redoParagraph(pit);
657 ParagraphMetrics const & pm = tm.parMetrics(pit);
659 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
660 + pm.ascent() - height_ / 2;
664 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
668 switch (cmd.action) {
671 flag.enabled(!buffer_->undostack().empty());
674 flag.enabled(!buffer_->redostack().empty());
676 case LFUN_FILE_INSERT:
677 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
678 case LFUN_FILE_INSERT_PLAINTEXT:
679 case LFUN_BOOKMARK_SAVE:
680 // FIXME: Actually, these LFUNS should be moved to Text
681 flag.enabled(cursor_.inTexted());
683 case LFUN_FONT_STATE:
684 case LFUN_LABEL_INSERT:
685 case LFUN_PARAGRAPH_GOTO:
686 // FIXME handle non-trivially
687 case LFUN_OUTLINE_UP:
688 case LFUN_OUTLINE_DOWN:
689 case LFUN_OUTLINE_IN:
690 case LFUN_OUTLINE_OUT:
692 case LFUN_REFERENCE_NEXT:
694 case LFUN_WORD_REPLACE:
697 case LFUN_MARK_TOGGLE:
698 case LFUN_SCREEN_RECENTER:
699 case LFUN_BIBTEX_DATABASE_ADD:
700 case LFUN_BIBTEX_DATABASE_DEL:
701 case LFUN_WORDS_COUNT:
702 case LFUN_NEXT_INSET_TOGGLE:
706 case LFUN_LABEL_GOTO: {
707 flag.enabled(!cmd.argument().empty()
708 || getInsetByCode<InsetRef>(cursor_, Inset::REF_CODE));
712 case LFUN_CHANGES_TRACK:
714 flag.setOnOff(buffer_->params().trackChanges);
717 case LFUN_CHANGES_OUTPUT:
718 flag.enabled(buffer_);
719 flag.setOnOff(buffer_->params().outputChanges);
722 case LFUN_CHANGES_MERGE:
723 case LFUN_CHANGE_NEXT:
724 case LFUN_ALL_CHANGES_ACCEPT:
725 case LFUN_ALL_CHANGES_REJECT:
726 // TODO: context-sensitive enabling of LFUNs
727 // In principle, these command should only be enabled if there
728 // is a change in the document. However, without proper
729 // optimizations, this will inevitably result in poor performance.
730 flag.enabled(buffer_);
733 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
734 flag.setOnOff(buffer_->params().compressed);
746 Update::flags BufferView::dispatch(FuncRequest const & cmd)
748 //lyxerr << BOOST_CURRENT_FUNCTION
749 // << [ cmd = " << cmd << "]" << endl;
751 // Make sure that the cached BufferView is correct.
752 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
753 << " action[" << cmd.action << ']'
754 << " arg[" << to_utf8(cmd.argument()) << ']'
755 << " x[" << cmd.x << ']'
756 << " y[" << cmd.y << ']'
757 << " button[" << cmd.button() << ']'
760 // FIXME: this should not be possible.
764 Cursor & cur = cursor_;
765 // Default Update flags.
766 Update::flags updateFlags = Update::Force | Update::FitCursor;
768 switch (cmd.action) {
771 cur.message(_("Undo"));
772 cur.clearSelection();
773 if (!textUndo(*this)) {
774 cur.message(_("No further undo information"));
775 updateFlags = Update::None;
781 cur.message(_("Redo"));
782 cur.clearSelection();
783 if (!textRedo(*this)) {
784 cur.message(_("No further redo information"));
785 updateFlags = Update::None;
790 case LFUN_FILE_INSERT:
792 menuInsertLyXFile(to_utf8(cmd.argument()));
795 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
797 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
800 case LFUN_FILE_INSERT_PLAINTEXT:
802 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
805 case LFUN_FONT_STATE:
806 cur.message(cur.currentState());
809 case LFUN_BOOKMARK_SAVE:
810 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
813 case LFUN_LABEL_GOTO: {
814 docstring label = cmd.argument();
817 getInsetByCode<InsetRef>(cursor_,
820 label = inset->getParam("reference");
821 // persistent=false: use temp_bookmark
831 case LFUN_PARAGRAPH_GOTO: {
832 int const id = convert<int>(to_utf8(cmd.argument()));
834 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
835 ParIterator par = b->getParFromID(id);
836 if (par == b->par_iterator_end()) {
838 << "No matching paragraph found! ["
839 << id << "]." << endl;
842 << "Paragraph " << par->id()
843 << " found in buffer `"
844 << b->fileName() << "'." << endl;
848 setCursor(makeDocIterator(par, 0));
851 // Switch to other buffer view and resend cmd
852 theLyXFunc().dispatch(FuncRequest(
853 LFUN_BUFFER_SWITCH, b->fileName()));
854 theLyXFunc().dispatch(cmd);
855 updateFlags = Update::None;
864 case LFUN_OUTLINE_UP:
865 toc::outline(toc::Up, cursor_);
866 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
867 updateLabels(*buffer_);
869 case LFUN_OUTLINE_DOWN:
870 toc::outline(toc::Down, cursor_);
871 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
872 updateLabels(*buffer_);
874 case LFUN_OUTLINE_IN:
875 toc::outline(toc::In, cursor_);
876 updateLabels(*buffer_);
878 case LFUN_OUTLINE_OUT:
879 toc::outline(toc::Out, cursor_);
880 updateLabels(*buffer_);
884 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
887 case LFUN_REFERENCE_NEXT: {
888 vector<Inset_code> tmp;
889 tmp.push_back(Inset::LABEL_CODE);
890 tmp.push_back(Inset::REF_CODE);
891 bv_funcs::gotoInset(this, tmp, true);
895 case LFUN_CHANGES_TRACK:
896 buffer_->params().trackChanges = !buffer_->params().trackChanges;
899 case LFUN_CHANGES_OUTPUT:
900 buffer_->params().outputChanges = !buffer_->params().outputChanges;
901 if (buffer_->params().outputChanges) {
902 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
903 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
904 LaTeXFeatures::isAvailable("xcolor");
906 if (!dvipost && !xcolorsoul) {
907 Alert::warning(_("Changes not shown in LaTeX output"),
908 _("Changes will not be highlighted in LaTeX output, "
909 "because neither dvipost nor xcolor/soul are installed.\n"
910 "Please install these packages or redefine "
911 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
912 } else if (!xcolorsoul) {
913 Alert::warning(_("Changes not shown in LaTeX output"),
914 _("Changes will not be highlighted in LaTeX output "
915 "when using pdflatex, because xcolor and soul are not installed.\n"
916 "Please install both packages or redefine "
917 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
922 case LFUN_CHANGE_NEXT:
923 findNextChange(this);
926 case LFUN_CHANGES_MERGE:
927 if (findNextChange(this))
928 showDialog("changes");
931 case LFUN_ALL_CHANGES_ACCEPT:
932 // select complete document
933 cursor_.reset(buffer_->inset());
934 cursor_.selHandle(true);
935 buffer_->text().cursorBottom(cursor_);
936 // accept everything in a single step to support atomic undo
937 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
940 case LFUN_ALL_CHANGES_REJECT:
941 // select complete document
942 cursor_.reset(buffer_->inset());
943 cursor_.selHandle(true);
944 buffer_->text().cursorBottom(cursor_);
945 // reject everything in a single step to support atomic undo
946 // Note: reject does not work recursively; the user may have to repeat the operation
947 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
954 case LFUN_WORD_REPLACE:
959 cur.clearSelection();
961 cur.message(from_utf8(N_("Mark off")));
965 cur.clearSelection();
968 cur.message(from_utf8(N_("Mark on")));
971 case LFUN_MARK_TOGGLE:
972 cur.clearSelection();
975 cur.message(from_utf8(N_("Mark removed")));
978 cur.message(from_utf8(N_("Mark set")));
983 case LFUN_SCREEN_RECENTER:
987 case LFUN_BIBTEX_DATABASE_ADD: {
988 Cursor tmpcur = cursor_;
989 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
990 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
993 if (inset->addDatabase(to_utf8(cmd.argument())))
994 buffer_->updateBibfilesCache();
999 case LFUN_BIBTEX_DATABASE_DEL: {
1000 Cursor tmpcur = cursor_;
1001 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
1002 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1003 Inset::BIBTEX_CODE);
1005 if (inset->delDatabase(to_utf8(cmd.argument())))
1006 buffer_->updateBibfilesCache();
1011 case LFUN_WORDS_COUNT: {
1012 DocIterator from, to;
1013 if (cur.selection()) {
1014 from = cur.selectionBegin();
1015 to = cur.selectionEnd();
1017 from = doc_iterator_begin(buffer_->inset());
1018 to = doc_iterator_end(buffer_->inset());
1020 int const count = countWords(from, to);
1023 if (cur.selection())
1024 message = bformat(_("%1$d words in selection."),
1027 message = bformat(_("%1$d words in document."),
1031 if (cur.selection())
1032 message = _("One word in selection.");
1034 message = _("One word in document.");
1037 Alert::information(_("Count words"), message);
1041 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1042 // turn compression on/off
1043 buffer_->params().compressed = !buffer_->params().compressed;
1046 case LFUN_NEXT_INSET_TOGGLE: {
1047 // this is the real function we want to invoke
1048 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1049 // if there is an inset at cursor, see whether it
1051 Inset * inset = cur.nextInset();
1052 if (inset && inset->isActive()) {
1053 Cursor tmpcur = cur;
1054 tmpcur.pushLeft(*inset);
1055 inset->dispatch(tmpcur, tmpcmd);
1056 if (tmpcur.result().dispatched()) {
1060 // if it did not work, try the underlying inset.
1061 if (!cur.result().dispatched())
1062 cur.dispatch(tmpcmd);
1064 if (cur.result().dispatched())
1065 cur.clearSelection();
1071 updateFlags = Update::None;
1078 docstring const BufferView::requestSelection()
1083 Cursor & cur = cursor_;
1085 if (!cur.selection()) {
1086 xsel_cache_.set = false;
1090 if (!xsel_cache_.set ||
1091 cur.top() != xsel_cache_.cursor ||
1092 cur.anchor_.top() != xsel_cache_.anchor)
1094 xsel_cache_.cursor = cur.top();
1095 xsel_cache_.anchor = cur.anchor_.top();
1096 xsel_cache_.set = cur.selection();
1097 return cur.selectionAsString(false);
1103 void BufferView::clearSelection()
1106 cursor_.clearSelection();
1107 // Clear the selection buffer. Otherwise a subsequent
1108 // middle-mouse-button paste would use the selection buffer,
1109 // not the more current external selection.
1110 cap::clearSelection();
1111 xsel_cache_.set = false;
1112 // The buffer did not really change, but this causes the
1113 // redraw we need because we cleared the selection above.
1119 void BufferView::workAreaResize(int width, int height)
1121 // Update from work area
1125 // The complete text metrics will be redone.
1126 text_metrics_.clear();
1133 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1135 pit_type pit = text.getPitNearY(*this, y);
1136 BOOST_ASSERT(pit != -1);
1137 Paragraph const & par = text.getPar(pit);
1139 LYXERR(Debug::DEBUG)
1140 << BOOST_CURRENT_FUNCTION
1145 InsetList::const_iterator iit = par.insetlist.begin();
1146 InsetList::const_iterator iend = par.insetlist.end();
1147 for (; iit != iend; ++iit) {
1148 Inset * const inset = iit->inset;
1149 if (inset->covers(*this, x, y)) {
1150 if (!inset->descendable())
1151 // No need to go further down if the inset is not
1155 size_t cell_number = inset->nargs();
1156 // Check all the inner cell.
1157 for (size_t i = 0; i != cell_number; ++i) {
1158 Text const * inner_text = inset->getText(i);
1161 Inset const * inset_deeper =
1162 getCoveringInset(*inner_text, x, y);
1164 return inset_deeper;
1168 LYXERR(Debug::DEBUG)
1169 << BOOST_CURRENT_FUNCTION
1170 << ": Hit inset: " << inset << endl;
1174 LYXERR(Debug::DEBUG)
1175 << BOOST_CURRENT_FUNCTION
1176 << ": No inset hit. " << endl;
1181 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1183 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1185 // This is only called for mouse related events including
1186 // LFUN_FILE_OPEN generated by drag-and-drop.
1187 FuncRequest cmd = cmd0;
1189 // E.g. Qt mouse press when no buffer
1194 cur.push(buffer_->inset());
1195 cur.selection() = cursor_.selection();
1197 // Either the inset under the cursor or the
1198 // surrounding Text will handle this event.
1200 // make sure we stay within the screen...
1201 cmd.y = min(max(cmd.y, -1), height_);
1203 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1205 // Get inset under mouse, if there is one.
1206 Inset const * covering_inset =
1207 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1208 if (covering_inset == last_inset_)
1209 // Same inset, no need to do anything...
1212 bool need_redraw = false;
1213 // const_cast because of setMouseHover().
1214 Inset * inset = const_cast<Inset *>(covering_inset);
1216 // Remove the hint on the last hovered inset (if any).
1217 need_redraw |= last_inset_->setMouseHover(false);
1219 // Highlighted the newly hovered inset (if any).
1220 need_redraw |= inset->setMouseHover(true);
1221 last_inset_ = inset;
1223 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1224 // not expose the button for redraw. We adjust here the metrics dimension
1225 // to enable a full redraw.
1226 // FIXME: It is possible to redraw only the area around the button!
1228 && metrics_info_.update_strategy == SingleParUpdate) {
1229 // FIXME: It should be possible to redraw only the area around
1230 // the button by doing this:
1232 //metrics_info_.singlepar = false;
1233 //metrics_info_.y1 = ymin of button;
1234 //metrics_info_.y2 = ymax of button;
1236 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1237 // between background updates and text updates. So we use the hammer
1238 // solution for now. We could also avoid the updateMetrics() below
1239 // by using the first and last pit of the CoordCache. Have a look
1240 // at Text::getPitNearY() to see what I mean.
1242 //metrics_info_.pit1 = first pit of CoordCache;
1243 //metrics_info_.pit2 = last pit of CoordCache;
1244 //metrics_info_.singlepar = false;
1245 //metrics_info_.y1 = 0;
1246 //metrics_info_.y2 = height_;
1248 updateMetrics(false);
1251 // This event (moving without mouse click) is not passed further.
1252 // This should be changed if it is further utilized.
1256 // Build temporary cursor.
1257 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1259 // Put anchor at the same position.
1262 // Try to dispatch to an non-editable inset near this position
1263 // via the temp cursor. If the inset wishes to change the real
1264 // cursor it has to do so explicitly by using
1265 // cur.bv().cursor() = cur; (or similar)
1267 inset->dispatch(cur, cmd);
1270 // Now dispatch to the temporary cursor. If the real cursor should
1271 // be modified, the inset's dispatch has to do so explicitly.
1272 if (!cur.result().dispatched())
1275 // Redraw if requested and necessary.
1276 if (cur.result().dispatched() && cur.result().update())
1277 return update(cur.result().update());
1283 void BufferView::scroll(int /*lines*/)
1288 // Text const * t = &buffer_->text();
1289 // int const line_height = defaultRowHeight();
1291 // // The new absolute coordinate
1292 // int new_top_y = top_y() + lines * line_height;
1294 // // Restrict to a valid value
1295 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1296 // new_top_y = std::max(0, new_top_y);
1298 // scrollDocView(new_top_y);
1303 void BufferView::setCursorFromRow(int row)
1308 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1311 buffer_->text().setCursor(cursor_, 0, 0);
1313 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1317 void BufferView::gotoLabel(docstring const & label)
1319 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1320 vector<docstring> labels;
1321 it->getLabelList(*buffer_, labels);
1322 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1331 TextMetrics const & BufferView::textMetrics(Text const * t) const
1333 return const_cast<BufferView *>(this)->textMetrics(t);
1337 TextMetrics & BufferView::textMetrics(Text const * t)
1339 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1340 if (tmc_it == text_metrics_.end()) {
1341 tmc_it = text_metrics_.insert(
1342 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1344 return tmc_it->second;
1348 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1351 return textMetrics(t).parMetrics(pit);
1355 int BufferView::workHeight() const
1361 void BufferView::setCursor(DocIterator const & dit)
1363 size_t const n = dit.depth();
1364 for (size_t i = 0; i < n; ++i)
1365 dit[i].inset().edit(cursor_, true);
1367 cursor_.setCursor(dit);
1368 cursor_.selection() = false;
1372 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1374 // Would be wrong to delete anything if we have a selection.
1375 if (cur.selection())
1378 bool need_anchor_change = false;
1379 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1380 need_anchor_change);
1382 if (need_anchor_change)
1388 updateLabels(*buffer_);
1390 updateMetrics(false);
1396 bool BufferView::mouseSetCursor(Cursor & cur)
1398 BOOST_ASSERT(&cur.bv() == this);
1400 // Has the cursor just left the inset?
1401 bool badcursor = false;
1402 bool leftinset = (&cursor_.inset() != &cur.inset());
1404 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1406 // do the dEPM magic if needed
1407 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1408 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1409 // the leftinset bool would not be necessary (badcursor instead).
1410 bool update = leftinset;
1411 if (!badcursor && cursor_.inTexted())
1412 update |= checkDepm(cur, cursor_);
1414 // if the cursor was in an empty script inset and the new
1415 // position is in the nucleus of the inset, notifyCursorLeaves
1416 // will kill the script inset itself. So we check all the
1417 // elements of the cursor to make sure that they are correct.
1418 // For an example, see bug 2933:
1419 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1420 // The code below could maybe be moved to a DocIterator method.
1421 //lyxerr << "cur before " << cur <<std::endl;
1422 DocIterator dit(cur.inset());
1423 dit.push_back(cur.bottom());
1425 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1426 dit.push_back(cur[i]);
1429 //lyxerr << "5 cur after" << dit <<std::endl;
1431 cursor_.setCursor(dit);
1432 cursor_.clearSelection();
1438 void BufferView::putSelectionAt(DocIterator const & cur,
1439 int length, bool backwards)
1441 cursor_.clearSelection();
1447 cursor_.pos() += length;
1448 cursor_.setSelection(cursor_, -length);
1450 cursor_.setSelection(cursor_, length);
1451 cap::saveSelection(cursor_);
1456 Cursor & BufferView::cursor()
1462 Cursor const & BufferView::cursor() const
1468 pit_type BufferView::anchor_ref() const
1474 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1476 return metrics_info_;
1480 // FIXME: We should split-up updateMetrics() for the singlepar case.
1481 void BufferView::updateMetrics(bool singlepar)
1483 Text & buftext = buffer_->text();
1484 TextMetrics & tm = textMetrics(&buftext);
1485 pit_type size = int(buftext.paragraphs().size());
1487 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1488 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1492 // If the paragraph metrics has changed, we can not
1493 // use the singlepar optimisation.
1495 // In Single Paragraph mode, rebreak only
1496 // the (main text, not inset!) paragraph containing the cursor.
1497 // (if this paragraph contains insets etc., rebreaking will
1498 // recursively descend)
1499 && tm.redoParagraph(cursor_.bottom().pit()))
1502 pit_type const pit = anchor_ref_;
1505 size_t const npit = buftext.paragraphs().size();
1507 // Rebreak anchor paragraph.
1509 tm.redoParagraph(pit);
1511 // Clear out the position cache in case of full screen redraw.
1513 coord_cache_.clear();
1515 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1517 // Redo paragraphs above anchor if necessary.
1519 while (y1 > 0 && pit1 > 0) {
1520 y1 -= tm.parMetrics(pit1).ascent();
1523 tm.redoParagraph(pit1);
1524 y1 -= tm.parMetrics(pit1).descent();
1528 // Take care of ascent of first line
1529 y1 -= tm.parMetrics(pit1).ascent();
1531 // Normalize anchor for next time
1535 // Grey at the beginning is ugly
1536 if (pit1 == 0 && y1 > 0) {
1542 // Redo paragraphs below the anchor if necessary.
1544 while (y2 < height_ && pit2 < int(npit) - 1) {
1545 y2 += tm.parMetrics(pit2).descent();
1548 tm.redoParagraph(pit2);
1549 y2 += tm.parMetrics(pit2).ascent();
1552 // Take care of descent of last line
1553 y2 += tm.parMetrics(pit2).descent();
1555 // The coordinates of all these paragraphs are correct, cache them
1557 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1558 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1559 ParagraphMetrics const & pm = tm.parMetrics(pit);
1561 parPos[pit] = Point(0, y);
1562 if (singlepar && pit == cursor_.bottom().pit()) {
1563 // In Single Paragraph mode, collect here the
1564 // y1 and y2 of the (one) paragraph the cursor is in
1565 y1 = y - pm.ascent();
1566 y2 = y + pm.descent();
1572 // collect cursor paragraph iter bounds
1573 pit1 = cursor_.bottom().pit();
1574 pit2 = cursor_.bottom().pit();
1577 LYXERR(Debug::DEBUG)
1578 << BOOST_CURRENT_FUNCTION
1581 << " pit1: " << pit1
1582 << " pit2: " << pit2
1583 << " npit: " << npit
1584 << " singlepar: " << singlepar
1588 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1589 singlepar? SingleParUpdate: FullScreenUpdate, size);
1591 if (lyxerr.debugging(Debug::WORKAREA)) {
1592 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1593 coord_cache_.dump();
1598 void BufferView::menuInsertLyXFile(string const & filenm)
1600 BOOST_ASSERT(cursor_.inTexted());
1601 string filename = filenm;
1603 if (filename.empty()) {
1604 // Launch a file browser
1606 string initpath = lyxrc.document_path;
1609 string const trypath = buffer_->filePath();
1610 // If directory is writeable, use this as default.
1611 if (isDirWriteable(FileName(trypath)))
1616 FileDialog fileDlg(_("Select LyX document to insert"),
1618 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1619 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support().absFilename(), "examples"))));
1621 FileDialog::Result result =
1622 fileDlg.open(from_utf8(initpath),
1623 FileFilterList(_("LyX Documents (*.lyx)")),
1626 if (result.first == FileDialog::Later)
1630 filename = to_utf8(result.second);
1632 // check selected filename
1633 if (filename.empty()) {
1634 // emit message signal.
1635 message(_("Canceled."));
1640 // Get absolute path of file and add ".lyx"
1641 // to the filename if necessary
1642 filename = fileSearch(string(), filename, "lyx").absFilename();
1644 docstring const disp_fn = makeDisplayPath(filename);
1645 // emit message signal.
1646 message(bformat(_("Inserting document %1$s..."), disp_fn));
1649 Buffer buf("", false);
1650 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1651 ErrorList & el = buffer_->errorList("Parse");
1652 // Copy the inserted document error list into the current buffer one.
1653 el = buf.errorList("Parse");
1654 recordUndo(cursor_);
1655 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1656 buf.params().textclass, el);
1657 res = _("Document %1$s inserted.");
1659 res = _("Could not insert document %1$s");
1661 // emit message signal.
1662 message(bformat(res, disp_fn));
1663 buffer_->errors("Parse");