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);
319 bool BufferView::fitCursor()
321 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
322 frontend::FontMetrics const & fm =
323 theFontMetrics(cursor_.getFont());
324 int const asc = fm.maxAscent();
325 int const des = fm.maxDescent();
326 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
327 if (p.y_ - asc >= 0 && p.y_ + des < height_)
335 bool BufferView::multiParSel()
337 if (!cursor_.selection())
339 bool ret = multiparsel_cache_;
340 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
341 // Either this, or previous selection spans paragraphs
342 return ret || multiparsel_cache_;
346 bool BufferView::update(Update::flags flags)
348 // last_inset_ points to the last visited inset. This pointer may become
349 // invalid because of keyboard editing. Since all such operations
350 // causes screen update(), I reset last_inset_ to avoid such a problem.
352 // This is close to a hot-path.
354 << BOOST_CURRENT_FUNCTION
355 << "[fitcursor = " << (flags & Update::FitCursor)
356 << ", forceupdate = " << (flags & Update::Force)
357 << ", singlepar = " << (flags & Update::SinglePar)
358 << "] buffer: " << buffer_ << endl;
360 // Check needed to survive LyX startup
364 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
366 // Update macro store
367 if (!(cursor().inMathed() && cursor().inMacroMode()))
368 buffer_->buildMacros();
370 // Now do the first drawing step if needed. This consists on updating
371 // the CoordCache in updateMetrics().
372 // The second drawing step is done in WorkArea::redraw() if needed.
374 // Case when no explicit update is requested.
376 // no need to redraw anything.
377 metrics_info_.update_strategy = NoScreenUpdate;
381 if (flags == Update::Decoration) {
382 metrics_info_.update_strategy = DecorationUpdate;
386 if (flags == Update::FitCursor
387 || flags == (Update::Decoration | Update::FitCursor)) {
388 bool const fit_cursor = fitCursor();
389 // tell the frontend to update the screen if needed.
391 updateMetrics(false);
394 if (flags & Update::Decoration) {
395 metrics_info_.update_strategy = DecorationUpdate;
398 // no screen update is needed.
399 metrics_info_.update_strategy = NoScreenUpdate;
403 bool full_metrics = flags & Update::Force;
404 if (flags & Update::MultiParSel)
405 full_metrics |= multiParSel();
407 bool const single_par = !full_metrics;
408 updateMetrics(single_par);
410 if (flags & Update::FitCursor && fitCursor())
411 updateMetrics(false);
413 // tell the frontend to update the screen.
418 void BufferView::updateScrollbar()
421 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
422 << " no text in updateScrollbar" << endl;
423 scrollbarParameters_.reset();
427 Text & t = buffer_->text();
428 TextMetrics & tm = text_metrics_[&t];
430 int const parsize = int(t.paragraphs().size() - 1);
431 if (anchor_ref_ > parsize) {
432 anchor_ref_ = parsize;
437 << BOOST_CURRENT_FUNCTION
438 << " Updating scrollbar: height: " << t.paragraphs().size()
439 << " curr par: " << cursor_.bottom().pit()
440 << " default height " << defaultRowHeight() << endl;
442 // It would be better to fix the scrollbar to understand
443 // values in [0..1] and divide everything by wh
445 // estimated average paragraph height:
449 int h = tm.parMetrics(anchor_ref_).height();
451 // Normalize anchor/offset (MV):
452 while (offset_ref_ > h && anchor_ref_ < parsize) {
455 h = tm.parMetrics(anchor_ref_).height();
457 // Look at paragraph heights on-screen
460 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
463 int const h2 = tm.parMetrics(pit).height();
469 int const hav = sumh / nh;
470 // More realistic average paragraph height
475 scrollbarParameters_.height = (parsize + 1) * wh_;
476 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
477 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
481 ScrollbarParameters const & BufferView::scrollbarParameters() const
483 return scrollbarParameters_;
487 void BufferView::scrollDocView(int value)
489 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
490 << "[ value = " << value << "]" << endl;
495 Text & t = buffer_->text();
496 TextMetrics & tm = text_metrics_[&t];
498 float const bar = value / float(wh_ * t.paragraphs().size());
500 anchor_ref_ = int(bar * t.paragraphs().size());
501 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
502 anchor_ref_ = int(t.paragraphs().size()) - 1;
504 tm.redoParagraph(anchor_ref_);
505 int const h = tm.parMetrics(anchor_ref_).height();
506 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
507 updateMetrics(false);
511 void BufferView::setCursorFromScrollbar()
516 Text & t = buffer_->text();
518 int const height = 2 * defaultRowHeight();
519 int const first = height;
520 int const last = height_ - height;
521 Cursor & cur = cursor_;
523 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
526 case bv_funcs::CUR_ABOVE:
527 // We reset the cursor because bv_funcs::status() does not
528 // work when the cursor is within mathed.
529 cur.reset(buffer_->inset());
530 t.setCursorFromCoordinates(cur, 0, first);
531 cur.clearSelection();
533 case bv_funcs::CUR_BELOW:
534 // We reset the cursor because bv_funcs::status() does not
535 // work when the cursor is within mathed.
536 cur.reset(buffer_->inset());
537 t.setCursorFromCoordinates(cur, 0, last);
538 cur.clearSelection();
540 case bv_funcs::CUR_INSIDE:
541 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
542 int const newy = min(last, max(y, first));
544 cur.reset(buffer_->inset());
545 t.setCursorFromCoordinates(cur, 0, newy);
551 Change const BufferView::getCurrentChange() const
553 if (!cursor_.selection())
554 return Change(Change::UNCHANGED);
556 DocIterator dit = cursor_.selectionBegin();
557 return dit.paragraph().lookupChange(dit.pos());
561 void BufferView::saveBookmark(unsigned int idx)
563 // tenatively save bookmark, id and pos will be used to
564 // acturately locate a bookmark in a 'live' lyx session.
565 // pit and pos will be updated with bottom level pit/pos
567 LyX::ref().session().bookmarks().save(
568 FileName(buffer_->fileName()),
569 cursor_.bottom().pit(),
570 cursor_.bottom().pos(),
571 cursor_.paragraph().id(),
576 // emit message signal.
577 message(_("Save bookmark"));
581 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
582 int top_id, pos_type top_pos)
584 cursor_.clearSelection();
586 // if a valid par_id is given, try it first
587 // This is the case for a 'live' bookmark when unique paragraph ID
588 // is used to track bookmarks.
590 ParIterator par = buffer_->getParFromID(top_id);
591 if (par != buffer_->par_iterator_end()) {
592 DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
593 // Some slices of the iterator may not be
594 // reachable (e.g. closed collapsable inset)
595 // so the dociterator may need to be
596 // shortened. Otherwise, setCursor may crash
597 // lyx when the cursor can not be set to these
599 size_t const n = dit.depth();
600 for (size_t i = 0; i < n; ++i)
601 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
606 // Note: return bottom (document) level pit.
607 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
610 // if top_id == 0, or searching through top_id failed
611 // This is the case for a 'restored' bookmark when only bottom
612 // (document level) pit was saved. Because of this, bookmark
613 // restoration is inaccurate. If a bookmark was within an inset,
614 // it will be restored to the left of the outmost inset that contains
616 if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
617 DocIterator it = doc_iterator_begin(buffer_->inset());
618 it.pit() = bottom_pit;
619 it.pos() = min(bottom_pos, it.paragraph().size());
621 return boost::make_tuple(it.pit(), it.pos(),
622 it.paragraph().id());
625 return boost::make_tuple(pit_type(0), pos_type(0), 0);
629 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
631 if (!lyxrc.rtl_support)
634 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
635 if (intl_->keymap == Intl::PRIMARY)
638 if (intl_->keymap == Intl::SECONDARY)
642 intl_->getTransManager().translateAndInsert(c, t, cur);
646 int BufferView::workWidth() const
652 void BufferView::center()
654 CursorSlice & bot = cursor_.bottom();
655 TextMetrics & tm = text_metrics_[bot.text()];
656 pit_type const pit = bot.pit();
657 tm.redoParagraph(pit);
658 ParagraphMetrics const & pm = tm.parMetrics(pit);
660 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
661 + pm.ascent() - height_ / 2;
665 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
669 Cursor & cur = cursor_;
671 switch (cmd.action) {
674 flag.enabled(!buffer_->undostack().empty());
677 flag.enabled(!buffer_->redostack().empty());
679 case LFUN_FILE_INSERT:
680 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
681 case LFUN_FILE_INSERT_PLAINTEXT:
682 case LFUN_BOOKMARK_SAVE:
683 // FIXME: Actually, these LFUNS should be moved to Text
684 flag.enabled(cur.inTexted());
686 case LFUN_FONT_STATE:
687 case LFUN_LABEL_INSERT:
688 case LFUN_PARAGRAPH_GOTO:
689 // FIXME handle non-trivially
690 case LFUN_OUTLINE_UP:
691 case LFUN_OUTLINE_DOWN:
692 case LFUN_OUTLINE_IN:
693 case LFUN_OUTLINE_OUT:
695 case LFUN_REFERENCE_NEXT:
699 case LFUN_MARK_TOGGLE:
700 case LFUN_SCREEN_RECENTER:
701 case LFUN_BIBTEX_DATABASE_ADD:
702 case LFUN_BIBTEX_DATABASE_DEL:
703 case LFUN_WORDS_COUNT:
704 case LFUN_NEXT_INSET_TOGGLE:
708 case LFUN_WORD_REPLACE:
709 flag.enabled(!cur.paragraph().isDeleted(cur.pos()));
712 case LFUN_LABEL_GOTO: {
713 flag.enabled(!cmd.argument().empty()
714 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
718 case LFUN_CHANGES_TRACK:
720 flag.setOnOff(buffer_->params().trackChanges);
723 case LFUN_CHANGES_OUTPUT:
724 flag.enabled(buffer_);
725 flag.setOnOff(buffer_->params().outputChanges);
728 case LFUN_CHANGES_MERGE:
729 case LFUN_CHANGE_NEXT:
730 case LFUN_ALL_CHANGES_ACCEPT:
731 case LFUN_ALL_CHANGES_REJECT:
732 // TODO: context-sensitive enabling of LFUNs
733 // In principle, these command should only be enabled if there
734 // is a change in the document. However, without proper
735 // optimizations, this will inevitably result in poor performance.
736 flag.enabled(buffer_);
739 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
740 flag.setOnOff(buffer_->params().compressed);
752 Update::flags BufferView::dispatch(FuncRequest const & cmd)
754 //lyxerr << BOOST_CURRENT_FUNCTION
755 // << [ cmd = " << cmd << "]" << endl;
757 // Make sure that the cached BufferView is correct.
758 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
759 << " action[" << cmd.action << ']'
760 << " arg[" << to_utf8(cmd.argument()) << ']'
761 << " x[" << cmd.x << ']'
762 << " y[" << cmd.y << ']'
763 << " button[" << cmd.button() << ']'
766 // FIXME: this should not be possible.
770 Cursor & cur = cursor_;
771 // Default Update flags.
772 Update::flags updateFlags = Update::Force | Update::FitCursor;
774 switch (cmd.action) {
777 cur.message(_("Undo"));
778 cur.clearSelection();
779 if (!textUndo(*this)) {
780 cur.message(_("No further undo information"));
781 updateFlags = Update::None;
786 cur.message(_("Redo"));
787 cur.clearSelection();
788 if (!textRedo(*this)) {
789 cur.message(_("No further redo information"));
790 updateFlags = Update::None;
794 case LFUN_FILE_INSERT:
796 menuInsertLyXFile(to_utf8(cmd.argument()));
799 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
801 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
804 case LFUN_FILE_INSERT_PLAINTEXT:
806 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
809 case LFUN_FONT_STATE:
810 cur.message(cur.currentState());
813 case LFUN_BOOKMARK_SAVE:
814 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
817 case LFUN_LABEL_GOTO: {
818 docstring label = cmd.argument();
821 getInsetByCode<InsetRef>(cursor_,
824 label = inset->getParam("reference");
825 // persistent=false: use temp_bookmark
835 case LFUN_PARAGRAPH_GOTO: {
836 int const id = convert<int>(to_utf8(cmd.argument()));
838 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
839 ParIterator par = b->getParFromID(id);
840 if (par == b->par_iterator_end()) {
842 << "No matching paragraph found! ["
843 << id << "]." << endl;
846 << "Paragraph " << par->id()
847 << " found in buffer `"
848 << b->fileName() << "'." << endl;
852 setCursor(makeDocIterator(par, 0));
854 // Switch to other buffer view and resend cmd
855 theLyXFunc().dispatch(FuncRequest(
856 LFUN_BUFFER_SWITCH, b->fileName()));
857 theLyXFunc().dispatch(cmd);
858 updateFlags = Update::None;
867 case LFUN_OUTLINE_UP:
868 toc::outline(toc::Up, cursor_);
869 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
870 updateLabels(*buffer_);
872 case LFUN_OUTLINE_DOWN:
873 toc::outline(toc::Down, cursor_);
874 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
875 updateLabels(*buffer_);
877 case LFUN_OUTLINE_IN:
878 toc::outline(toc::In, cursor_);
879 updateLabels(*buffer_);
881 case LFUN_OUTLINE_OUT:
882 toc::outline(toc::Out, cursor_);
883 updateLabels(*buffer_);
887 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
890 case LFUN_REFERENCE_NEXT: {
891 vector<Inset_code> tmp;
892 tmp.push_back(Inset::LABEL_CODE);
893 tmp.push_back(Inset::REF_CODE);
894 bv_funcs::gotoInset(this, tmp, true);
898 case LFUN_CHANGES_TRACK:
899 buffer_->params().trackChanges = !buffer_->params().trackChanges;
902 case LFUN_CHANGES_OUTPUT:
903 buffer_->params().outputChanges = !buffer_->params().outputChanges;
904 if (buffer_->params().outputChanges) {
905 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
906 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
907 LaTeXFeatures::isAvailable("xcolor");
909 if (!dvipost && !xcolorsoul) {
910 Alert::warning(_("Changes not shown in LaTeX output"),
911 _("Changes will not be highlighted in LaTeX output, "
912 "because neither dvipost nor xcolor/soul are installed.\n"
913 "Please install these packages or redefine "
914 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
915 } else if (!xcolorsoul) {
916 Alert::warning(_("Changes not shown in LaTeX output"),
917 _("Changes will not be highlighted in LaTeX output "
918 "when using pdflatex, because xcolor and soul are not installed.\n"
919 "Please install both packages or redefine "
920 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
925 case LFUN_CHANGE_NEXT:
926 findNextChange(this);
929 case LFUN_CHANGES_MERGE:
930 if (findNextChange(this))
931 showDialog("changes");
934 case LFUN_ALL_CHANGES_ACCEPT:
935 // select complete document
936 cursor_.reset(buffer_->inset());
937 cursor_.selHandle(true);
938 buffer_->text().cursorBottom(cursor_);
939 // accept everything in a single step to support atomic undo
940 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
943 case LFUN_ALL_CHANGES_REJECT:
944 // select complete document
945 cursor_.reset(buffer_->inset());
946 cursor_.selHandle(true);
947 buffer_->text().cursorBottom(cursor_);
948 // reject everything in a single step to support atomic undo
949 // Note: reject does not work recursively; the user may have to repeat the operation
950 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
957 case LFUN_WORD_REPLACE:
962 cur.clearSelection();
964 cur.message(from_utf8(N_("Mark off")));
968 cur.clearSelection();
971 cur.message(from_utf8(N_("Mark on")));
974 case LFUN_MARK_TOGGLE:
975 cur.clearSelection();
978 cur.message(from_utf8(N_("Mark removed")));
981 cur.message(from_utf8(N_("Mark set")));
986 case LFUN_SCREEN_RECENTER:
990 case LFUN_BIBTEX_DATABASE_ADD: {
991 Cursor tmpcur = cursor_;
992 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
993 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
996 if (inset->addDatabase(to_utf8(cmd.argument())))
997 buffer_->updateBibfilesCache();
1002 case LFUN_BIBTEX_DATABASE_DEL: {
1003 Cursor tmpcur = cursor_;
1004 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
1005 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1006 Inset::BIBTEX_CODE);
1008 if (inset->delDatabase(to_utf8(cmd.argument())))
1009 buffer_->updateBibfilesCache();
1014 case LFUN_WORDS_COUNT: {
1015 DocIterator from, to;
1016 if (cur.selection()) {
1017 from = cur.selectionBegin();
1018 to = cur.selectionEnd();
1020 from = doc_iterator_begin(buffer_->inset());
1021 to = doc_iterator_end(buffer_->inset());
1023 int const count = countWords(from, to);
1026 if (cur.selection())
1027 message = bformat(_("%1$d words in selection."),
1030 message = bformat(_("%1$d words in document."),
1034 if (cur.selection())
1035 message = _("One word in selection.");
1037 message = _("One word in document.");
1040 Alert::information(_("Count words"), message);
1044 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1045 // turn compression on/off
1046 buffer_->params().compressed = !buffer_->params().compressed;
1049 case LFUN_NEXT_INSET_TOGGLE: {
1050 // this is the real function we want to invoke
1051 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1052 // if there is an inset at cursor, see whether it
1054 Inset * inset = cur.nextInset();
1055 if (inset && inset->isActive()) {
1056 Cursor tmpcur = cur;
1057 tmpcur.pushLeft(*inset);
1058 inset->dispatch(tmpcur, tmpcmd);
1059 if (tmpcur.result().dispatched()) {
1063 // if it did not work, try the underlying inset.
1064 if (!cur.result().dispatched())
1065 cur.dispatch(tmpcmd);
1067 if (cur.result().dispatched())
1068 cur.clearSelection();
1074 updateFlags = Update::None;
1081 docstring const BufferView::requestSelection()
1086 Cursor & cur = cursor_;
1088 if (!cur.selection()) {
1089 xsel_cache_.set = false;
1093 if (!xsel_cache_.set ||
1094 cur.top() != xsel_cache_.cursor ||
1095 cur.anchor_.top() != xsel_cache_.anchor)
1097 xsel_cache_.cursor = cur.top();
1098 xsel_cache_.anchor = cur.anchor_.top();
1099 xsel_cache_.set = cur.selection();
1100 return cur.selectionAsString(false);
1106 void BufferView::clearSelection()
1109 cursor_.clearSelection();
1110 // Clear the selection buffer. Otherwise a subsequent
1111 // middle-mouse-button paste would use the selection buffer,
1112 // not the more current external selection.
1113 cap::clearSelection();
1114 xsel_cache_.set = false;
1115 // The buffer did not really change, but this causes the
1116 // redraw we need because we cleared the selection above.
1122 void BufferView::workAreaResize(int width, int height)
1124 // Update from work area
1128 // The complete text metrics will be redone.
1129 text_metrics_.clear();
1136 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1138 pit_type pit = text.getPitNearY(*this, y);
1139 BOOST_ASSERT(pit != -1);
1140 Paragraph const & par = text.getPar(pit);
1142 LYXERR(Debug::DEBUG)
1143 << BOOST_CURRENT_FUNCTION
1148 InsetList::const_iterator iit = par.insetlist.begin();
1149 InsetList::const_iterator iend = par.insetlist.end();
1150 for (; iit != iend; ++iit) {
1151 Inset * const inset = iit->inset;
1152 if (inset->covers(*this, x, y)) {
1153 if (!inset->descendable())
1154 // No need to go further down if the inset is not
1158 size_t cell_number = inset->nargs();
1159 // Check all the inner cell.
1160 for (size_t i = 0; i != cell_number; ++i) {
1161 Text const * inner_text = inset->getText(i);
1164 Inset const * inset_deeper =
1165 getCoveringInset(*inner_text, x, y);
1167 return inset_deeper;
1171 LYXERR(Debug::DEBUG)
1172 << BOOST_CURRENT_FUNCTION
1173 << ": Hit inset: " << inset << endl;
1177 LYXERR(Debug::DEBUG)
1178 << BOOST_CURRENT_FUNCTION
1179 << ": No inset hit. " << endl;
1184 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1186 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1188 // This is only called for mouse related events including
1189 // LFUN_FILE_OPEN generated by drag-and-drop.
1190 FuncRequest cmd = cmd0;
1192 // E.g. Qt mouse press when no buffer
1197 cur.push(buffer_->inset());
1198 cur.selection() = cursor_.selection();
1200 // Either the inset under the cursor or the
1201 // surrounding Text will handle this event.
1203 // make sure we stay within the screen...
1204 cmd.y = min(max(cmd.y, -1), height_);
1206 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1208 // Get inset under mouse, if there is one.
1209 Inset const * covering_inset =
1210 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1211 if (covering_inset == last_inset_)
1212 // Same inset, no need to do anything...
1215 bool need_redraw = false;
1216 // const_cast because of setMouseHover().
1217 Inset * inset = const_cast<Inset *>(covering_inset);
1219 // Remove the hint on the last hovered inset (if any).
1220 need_redraw |= last_inset_->setMouseHover(false);
1222 // Highlighted the newly hovered inset (if any).
1223 need_redraw |= inset->setMouseHover(true);
1224 last_inset_ = inset;
1226 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1227 // not expose the button for redraw. We adjust here the metrics dimension
1228 // to enable a full redraw.
1229 // FIXME: It is possible to redraw only the area around the button!
1231 && metrics_info_.update_strategy == SingleParUpdate) {
1232 // FIXME: It should be possible to redraw only the area around
1233 // the button by doing this:
1235 //metrics_info_.singlepar = false;
1236 //metrics_info_.y1 = ymin of button;
1237 //metrics_info_.y2 = ymax of button;
1239 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1240 // between background updates and text updates. So we use the hammer
1241 // solution for now. We could also avoid the updateMetrics() below
1242 // by using the first and last pit of the CoordCache. Have a look
1243 // at Text::getPitNearY() to see what I mean.
1245 //metrics_info_.pit1 = first pit of CoordCache;
1246 //metrics_info_.pit2 = last pit of CoordCache;
1247 //metrics_info_.singlepar = false;
1248 //metrics_info_.y1 = 0;
1249 //metrics_info_.y2 = height_;
1251 updateMetrics(false);
1254 // This event (moving without mouse click) is not passed further.
1255 // This should be changed if it is further utilized.
1259 // Build temporary cursor.
1260 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1262 // Put anchor at the same position.
1265 // Try to dispatch to an non-editable inset near this position
1266 // via the temp cursor. If the inset wishes to change the real
1267 // cursor it has to do so explicitly by using
1268 // cur.bv().cursor() = cur; (or similar)
1270 inset->dispatch(cur, cmd);
1273 // Now dispatch to the temporary cursor. If the real cursor should
1274 // be modified, the inset's dispatch has to do so explicitly.
1275 if (!cur.result().dispatched())
1278 // Redraw if requested and necessary.
1279 if (cur.result().dispatched() && cur.result().update())
1280 return update(cur.result().update());
1286 void BufferView::scroll(int /*lines*/)
1291 // Text const * t = &buffer_->text();
1292 // int const line_height = defaultRowHeight();
1294 // // The new absolute coordinate
1295 // int new_top_y = top_y() + lines * line_height;
1297 // // Restrict to a valid value
1298 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1299 // new_top_y = std::max(0, new_top_y);
1301 // scrollDocView(new_top_y);
1306 void BufferView::setCursorFromRow(int row)
1311 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1314 buffer_->text().setCursor(cursor_, 0, 0);
1316 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1320 void BufferView::gotoLabel(docstring const & label)
1322 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1323 vector<docstring> labels;
1324 it->getLabelList(*buffer_, labels);
1325 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1334 TextMetrics const & BufferView::textMetrics(Text const * t) const
1336 return const_cast<BufferView *>(this)->textMetrics(t);
1340 TextMetrics & BufferView::textMetrics(Text const * t)
1342 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1343 if (tmc_it == text_metrics_.end()) {
1344 tmc_it = text_metrics_.insert(
1345 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1347 return tmc_it->second;
1351 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1354 return textMetrics(t).parMetrics(pit);
1358 int BufferView::workHeight() const
1364 void BufferView::setCursor(DocIterator const & dit)
1366 size_t const n = dit.depth();
1367 for (size_t i = 0; i < n; ++i)
1368 dit[i].inset().edit(cursor_, true);
1370 cursor_.setCursor(dit);
1371 cursor_.selection() = false;
1375 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1377 // Would be wrong to delete anything if we have a selection.
1378 if (cur.selection())
1381 bool need_anchor_change = false;
1382 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1383 need_anchor_change);
1385 if (need_anchor_change)
1391 updateLabels(*buffer_);
1393 updateMetrics(false);
1399 bool BufferView::mouseSetCursor(Cursor & cur)
1401 BOOST_ASSERT(&cur.bv() == this);
1403 // Has the cursor just left the inset?
1404 bool badcursor = false;
1405 bool leftinset = (&cursor_.inset() != &cur.inset());
1407 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1409 // do the dEPM magic if needed
1410 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1411 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1412 // the leftinset bool would not be necessary (badcursor instead).
1413 bool update = leftinset;
1414 if (!badcursor && cursor_.inTexted())
1415 update |= checkDepm(cur, cursor_);
1417 // if the cursor was in an empty script inset and the new
1418 // position is in the nucleus of the inset, notifyCursorLeaves
1419 // will kill the script inset itself. So we check all the
1420 // elements of the cursor to make sure that they are correct.
1421 // For an example, see bug 2933:
1422 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1423 // The code below could maybe be moved to a DocIterator method.
1424 //lyxerr << "cur before " << cur <<std::endl;
1425 DocIterator dit(cur.inset());
1426 dit.push_back(cur.bottom());
1428 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1429 dit.push_back(cur[i]);
1432 //lyxerr << "5 cur after" << dit <<std::endl;
1434 cursor_.setCursor(dit);
1435 cursor_.boundary(cur.boundary());
1436 cursor_.clearSelection();
1442 void BufferView::putSelectionAt(DocIterator const & cur,
1443 int length, bool backwards)
1445 cursor_.clearSelection();
1451 cursor_.pos() += length;
1452 cursor_.setSelection(cursor_, -length);
1454 cursor_.setSelection(cursor_, length);
1455 cap::saveSelection(cursor_);
1460 Cursor & BufferView::cursor()
1466 Cursor const & BufferView::cursor() const
1472 pit_type BufferView::anchor_ref() const
1478 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1480 return metrics_info_;
1484 // FIXME: We should split-up updateMetrics() for the singlepar case.
1485 void BufferView::updateMetrics(bool singlepar)
1487 Text & buftext = buffer_->text();
1488 TextMetrics & tm = textMetrics(&buftext);
1489 pit_type size = int(buftext.paragraphs().size());
1491 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1492 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1496 // If the paragraph metrics has changed, we can not
1497 // use the singlepar optimisation.
1499 // In Single Paragraph mode, rebreak only
1500 // the (main text, not inset!) paragraph containing the cursor.
1501 // (if this paragraph contains insets etc., rebreaking will
1502 // recursively descend)
1503 && tm.redoParagraph(cursor_.bottom().pit()))
1506 pit_type const pit = anchor_ref_;
1509 size_t const npit = buftext.paragraphs().size();
1511 // Rebreak anchor paragraph.
1513 tm.redoParagraph(pit);
1515 // Clear out the position cache in case of full screen redraw.
1517 coord_cache_.clear();
1519 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1521 // Redo paragraphs above anchor if necessary.
1523 while (y1 > 0 && pit1 > 0) {
1524 y1 -= tm.parMetrics(pit1).ascent();
1527 tm.redoParagraph(pit1);
1528 y1 -= tm.parMetrics(pit1).descent();
1532 // Take care of ascent of first line
1533 y1 -= tm.parMetrics(pit1).ascent();
1535 // Normalize anchor for next time
1539 // Grey at the beginning is ugly
1540 if (pit1 == 0 && y1 > 0) {
1546 // Redo paragraphs below the anchor if necessary.
1548 while (y2 < height_ && pit2 < int(npit) - 1) {
1549 y2 += tm.parMetrics(pit2).descent();
1552 tm.redoParagraph(pit2);
1553 y2 += tm.parMetrics(pit2).ascent();
1556 // Take care of descent of last line
1557 y2 += tm.parMetrics(pit2).descent();
1559 // The coordinates of all these paragraphs are correct, cache them
1561 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1562 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1563 ParagraphMetrics const & pm = tm.parMetrics(pit);
1565 parPos[pit] = Point(0, y);
1566 if (singlepar && pit == cursor_.bottom().pit()) {
1567 // In Single Paragraph mode, collect here the
1568 // y1 and y2 of the (one) paragraph the cursor is in
1569 y1 = y - pm.ascent();
1570 y2 = y + pm.descent();
1576 // collect cursor paragraph iter bounds
1577 pit1 = cursor_.bottom().pit();
1578 pit2 = cursor_.bottom().pit();
1581 LYXERR(Debug::DEBUG)
1582 << BOOST_CURRENT_FUNCTION
1585 << " pit1: " << pit1
1586 << " pit2: " << pit2
1587 << " npit: " << npit
1588 << " singlepar: " << singlepar
1592 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1593 singlepar? SingleParUpdate: FullScreenUpdate, size);
1595 if (lyxerr.debugging(Debug::WORKAREA)) {
1596 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1597 coord_cache_.dump();
1602 void BufferView::menuInsertLyXFile(string const & filenm)
1604 BOOST_ASSERT(cursor_.inTexted());
1605 string filename = filenm;
1607 if (filename.empty()) {
1608 // Launch a file browser
1610 string initpath = lyxrc.document_path;
1613 string const trypath = buffer_->filePath();
1614 // If directory is writeable, use this as default.
1615 if (isDirWriteable(FileName(trypath)))
1620 FileDialog fileDlg(_("Select LyX document to insert"),
1622 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1623 make_pair(_("Examples|#E#e"),
1624 from_utf8(addPath(package().system_support().absFilename(),
1627 FileDialog::Result result =
1628 fileDlg.open(from_utf8(initpath),
1629 FileFilterList(_("LyX Documents (*.lyx)")),
1632 if (result.first == FileDialog::Later)
1636 filename = to_utf8(result.second);
1638 // check selected filename
1639 if (filename.empty()) {
1640 // emit message signal.
1641 message(_("Canceled."));
1646 // Get absolute path of file and add ".lyx"
1647 // to the filename if necessary
1648 filename = fileSearch(string(), filename, "lyx").absFilename();
1650 docstring const disp_fn = makeDisplayPath(filename);
1651 // emit message signal.
1652 message(bformat(_("Inserting document %1$s..."), disp_fn));
1655 Buffer buf("", false);
1656 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1657 ErrorList & el = buffer_->errorList("Parse");
1658 // Copy the inserted document error list into the current buffer one.
1659 el = buf.errorList("Parse");
1660 recordUndo(cursor_);
1661 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1662 buf.params().textclass, el);
1663 res = _("Document %1$s inserted.");
1665 res = _("Could not insert document %1$s");
1667 // emit message signal.
1668 message(bformat(res, disp_fn));
1669 buffer_->errors("Parse");