3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetText.h"
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include "support/bind.h"
107 #include "support/shared_ptr.h"
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 398; // uwestoehr: support for \mathscr
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope,
168 bool record_docits = false);
170 void setLabel(ParIterator & it, UpdateType utype) const;
172 void collectRelatives(BufferSet & bufs) const;
174 /** If we have branches that use the file suffix
175 feature, return the file name with suffix appended.
177 support::FileName exportFileName() const;
184 mutable TexRow texrow;
186 /// need to regenerate .tex?
190 mutable bool lyx_clean;
192 /// is autosave needed?
193 mutable bool bak_clean;
195 /// is this a unnamed file (New...)?
201 /// name of the file the buffer is associated with.
204 /** Set to true only when the file is fully loaded.
205 * Used to prevent the premature generation of previews
206 * and by the citation inset.
208 bool file_fully_loaded;
211 mutable TocBackend toc_backend;
214 typedef pair<DocIterator, MacroData> ScopeMacro;
215 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
216 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
217 /// map from the macro name to the position map,
218 /// which maps the macro definition position to the scope and the MacroData.
219 NamePositionScopeMacroMap macros;
220 /// This seem to change the way Buffer::getMacro() works
221 mutable bool macro_lock;
223 /// positions of child buffers in the buffer
224 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
225 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
226 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
227 /// position of children buffers in this buffer
228 BufferPositionMap children_positions;
229 /// map from children inclusion positions to their scope and their buffer
230 PositionScopeBufferMap position_to_children;
232 /// Container for all sort of Buffer dependant errors.
233 map<string, ErrorList> errorLists;
235 /// timestamp and checksum used to test if the file has been externally
236 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
238 unsigned long checksum_;
241 frontend::WorkAreaManager * wa_;
243 frontend::GuiBufferDelegate * gui_;
248 /// A cache for the bibfiles (including bibfiles of loaded child
249 /// documents), needed for appropriate update of natbib labels.
250 mutable support::FileNameList bibfiles_cache_;
252 // FIXME The caching mechanism could be improved. At present, we have a
253 // cache for each Buffer, that caches all the bibliography info for that
254 // Buffer. A more efficient solution would be to have a global cache per
255 // file, and then to construct the Buffer's bibinfo from that.
256 /// A cache for bibliography info
257 mutable BiblioInfo bibinfo_;
258 /// whether the bibinfo cache is valid
259 bool bibinfo_cache_valid_;
260 /// Cache of timestamps of .bib files
261 map<FileName, time_t> bibfile_status_;
263 mutable RefCache ref_cache_;
265 /// our Text that should be wrapped in an InsetText
268 /// This is here to force the test to be done whenever parent_buffer
270 Buffer const * parent() const {
271 // if parent_buffer is not loaded, then it has been unloaded,
272 // which means that parent_buffer is an invalid pointer. So we
273 // set it to null in that case.
274 // however, the BufferList doesn't know about cloned buffers, so
275 // they will always be regarded as unloaded. in that case, we hope
277 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
279 return parent_buffer;
282 void setParent(Buffer const * pb) {
284 && parent_buffer && pb && parent_buffer != pb)
285 LYXERR0("Warning: a buffer should not have two parents!");
289 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
290 /// This one is useful for preview detached in a thread.
291 Buffer const * cloned_buffer_;
292 /// are we in the process of exporting this buffer?
293 mutable bool doing_export;
296 /// So we can force access via the accessors.
297 mutable Buffer const * parent_buffer;
302 /// Creates the per buffer temporary directory
303 static FileName createBufferTmpDir()
306 // We are in our own directory. Why bother to mangle name?
307 // In fact I wrote this code to circumvent a problematic behaviour
308 // (bug?) of EMX mkstemp().
309 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
310 convert<string>(count++));
312 if (!tmpfl.createDirectory(0777)) {
313 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
314 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
315 from_utf8(tmpfl.absFileName())));
321 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
322 Buffer const * cloned_buffer)
323 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
324 read_only(readonly_), filename(file), file_fully_loaded(false),
325 toc_backend(owner), macro_lock(false), timestamp_(0),
326 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
327 cloned_buffer_(cloned_buffer), doing_export(false), parent_buffer(0)
329 if (!cloned_buffer_) {
330 temppath = createBufferTmpDir();
331 lyxvc.setBuffer(owner_);
333 wa_ = new frontend::WorkAreaManager;
336 temppath = cloned_buffer_->d->temppath;
337 file_fully_loaded = true;
338 params = cloned_buffer_->d->params;
339 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
340 bibinfo_ = cloned_buffer_->d->bibinfo_;
341 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
342 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
346 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
347 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
349 LYXERR(Debug::INFO, "Buffer::Buffer()");
351 d->inset = new InsetText(*cloned_buffer->d->inset);
352 d->inset->setBuffer(*this);
353 // FIXME: optimize this loop somewhat, maybe by creating a new
354 // general recursive Inset::setId().
355 DocIterator it = doc_iterator_begin(this);
356 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
357 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
358 it.paragraph().setId(cloned_it.paragraph().id());
360 d->inset = new InsetText(this);
361 d->inset->setAutoBreakRows(true);
362 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
368 LYXERR(Debug::INFO, "Buffer::~Buffer()");
369 // here the buffer should take care that it is
370 // saved properly, before it goes into the void.
372 // GuiView already destroyed
376 // No need to do additional cleanups for internal buffer.
381 // loop over children
382 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
383 Impl::BufferPositionMap::iterator end = d->children_positions.end();
384 for (; it != end; ++it) {
385 Buffer * child = const_cast<Buffer *>(it->first);
386 if (d->cloned_buffer_)
388 // The child buffer might have been closed already.
389 else if (theBufferList().isLoaded(child))
390 theBufferList().releaseChild(this, child);
394 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
395 msg += emergencyWrite();
396 Alert::warning(_("Attempting to close changed document!"), msg);
399 // clear references to children in macro tables
400 d->children_positions.clear();
401 d->position_to_children.clear();
403 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
404 Alert::warning(_("Could not remove temporary directory"),
405 bformat(_("Could not remove the temporary directory %1$s"),
406 from_utf8(d->temppath.absFileName())));
409 // Remove any previewed LaTeX snippets associated with this buffer.
411 thePreviews().removeLoader(*this);
417 Buffer * Buffer::clone() const
419 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
420 buffer_clone->d->macro_lock = true;
421 buffer_clone->d->children_positions.clear();
422 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
423 // math macro caches need to be rethought and simplified.
424 // I am not sure wether we should handle Buffer cloning here or in BufferList.
425 // Right now BufferList knows nothing about buffer clones.
426 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
427 Impl::BufferPositionMap::iterator end = d->children_positions.end();
428 for (; it != end; ++it) {
429 DocIterator dit = it->second.clone(buffer_clone);
430 dit.setBuffer(buffer_clone);
431 Buffer * child = const_cast<Buffer *>(it->first);
432 Buffer * child_clone = child->clone();
433 Inset * inset = dit.nextInset();
434 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
435 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
436 inset_inc->setChildBuffer(child_clone);
437 child_clone->d->setParent(buffer_clone);
438 buffer_clone->setChild(dit, child_clone);
440 buffer_clone->d->macro_lock = false;
445 bool Buffer::isClone() const
447 return d->cloned_buffer_;
451 void Buffer::changed(bool update_metrics) const
454 d->wa_->redrawAll(update_metrics);
458 frontend::WorkAreaManager & Buffer::workAreaManager() const
460 LASSERT(d->wa_, /**/);
465 Text & Buffer::text() const
467 return d->inset->text();
471 Inset & Buffer::inset() const
477 BufferParams & Buffer::params()
483 BufferParams const & Buffer::params() const
489 ParagraphList & Buffer::paragraphs()
491 return text().paragraphs();
495 ParagraphList const & Buffer::paragraphs() const
497 return text().paragraphs();
501 LyXVC & Buffer::lyxvc()
507 LyXVC const & Buffer::lyxvc() const
513 string const Buffer::temppath() const
515 return d->temppath.absFileName();
519 TexRow & Buffer::texrow()
525 TexRow const & Buffer::texrow() const
531 TocBackend & Buffer::tocBackend() const
533 return d->toc_backend;
537 Undo & Buffer::undo()
543 void Buffer::setChild(DocIterator const & dit, Buffer * child)
545 d->children_positions[child] = dit;
549 string Buffer::latexName(bool const no_path) const
551 FileName latex_name =
552 makeLatexName(d->exportFileName());
553 return no_path ? latex_name.onlyFileName()
554 : latex_name.absFileName();
558 FileName Buffer::Impl::exportFileName() const
560 docstring const branch_suffix =
561 params.branchlist().getFileNameSuffix();
562 if (branch_suffix.empty())
565 string const name = filename.onlyFileNameWithoutExt()
566 + to_utf8(branch_suffix);
567 FileName res(filename.onlyPath().absFileName() + "/" + name);
568 res.changeExtension(filename.extension());
574 string Buffer::logName(LogType * type) const
576 string const filename = latexName(false);
578 if (filename.empty()) {
584 string const path = temppath();
586 FileName const fname(addName(temppath(),
587 onlyFileName(changeExtension(filename,
590 // FIXME: how do we know this is the name of the build log?
591 FileName const bname(
592 addName(path, onlyFileName(
593 changeExtension(filename,
594 formats.extension(bufferFormat()) + ".out"))));
596 // Also consider the master buffer log file
597 FileName masterfname = fname;
599 if (masterBuffer() != this) {
600 string const mlogfile = masterBuffer()->logName(&mtype);
601 masterfname = FileName(mlogfile);
604 // If no Latex log or Build log is newer, show Build log
605 if (bname.exists() &&
606 ((!fname.exists() && !masterfname.exists())
607 || (fname.lastModified() < bname.lastModified()
608 && masterfname.lastModified() < bname.lastModified()))) {
609 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
612 return bname.absFileName();
613 // If we have a newer master file log or only a master log, show this
614 } else if (fname != masterfname
615 && (!fname.exists() && (masterfname.exists()
616 || fname.lastModified() < masterfname.lastModified()))) {
617 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
620 return masterfname.absFileName();
622 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
625 return fname.absFileName();
629 void Buffer::setReadonly(bool const flag)
631 if (d->read_only != flag) {
638 void Buffer::setFileName(string const & newfile)
640 d->filename = makeAbsPath(newfile);
641 setReadonly(d->filename.isReadOnly());
646 int Buffer::readHeader(Lexer & lex)
648 int unknown_tokens = 0;
650 int begin_header_line = -1;
652 // Initialize parameters that may be/go lacking in header:
653 params().branchlist().clear();
654 params().preamble.erase();
655 params().options.erase();
656 params().master.erase();
657 params().float_placement.erase();
658 params().paperwidth.erase();
659 params().paperheight.erase();
660 params().leftmargin.erase();
661 params().rightmargin.erase();
662 params().topmargin.erase();
663 params().bottommargin.erase();
664 params().headheight.erase();
665 params().headsep.erase();
666 params().footskip.erase();
667 params().columnsep.erase();
668 params().fontsCJK.erase();
669 params().listings_params.clear();
670 params().clearLayoutModules();
671 params().clearRemovedModules();
672 params().clearIncludedChildren();
673 params().pdfoptions().clear();
674 params().indiceslist().clear();
675 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
676 params().isbackgroundcolor = false;
677 params().fontcolor = lyx::rgbFromHexName("#000000");
678 params().isfontcolor = false;
679 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
680 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
681 params().html_latex_start.clear();
682 params().html_latex_end.clear();
683 params().html_math_img_scale = 1.0;
684 params().output_sync_macro.erase();
686 for (int i = 0; i < 4; ++i) {
687 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
688 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
691 ErrorList & errorList = d->errorLists["Parse"];
700 if (token == "\\end_header")
704 if (token == "\\begin_header") {
705 begin_header_line = line;
709 LYXERR(Debug::PARSER, "Handling document header token: `"
712 string unknown = params().readToken(lex, token, d->filename.onlyPath());
713 if (!unknown.empty()) {
714 if (unknown[0] != '\\' && token == "\\textclass") {
715 Alert::warning(_("Unknown document class"),
716 bformat(_("Using the default document class, because the "
717 "class %1$s is unknown."), from_utf8(unknown)));
720 docstring const s = bformat(_("Unknown token: "
724 errorList.push_back(ErrorItem(_("Document header error"),
729 if (begin_header_line) {
730 docstring const s = _("\\begin_header is missing");
731 errorList.push_back(ErrorItem(_("Document header error"),
735 params().makeDocumentClass();
737 return unknown_tokens;
742 // changed to be public and have one parameter
743 // Returns true if "\end_document" is not read (Asger)
744 bool Buffer::readDocument(Lexer & lex)
746 ErrorList & errorList = d->errorLists["Parse"];
749 if (!lex.checkFor("\\begin_document")) {
750 docstring const s = _("\\begin_document is missing");
751 errorList.push_back(ErrorItem(_("Document header error"),
755 // we are reading in a brand new document
756 LASSERT(paragraphs().empty(), /**/);
760 if (params().outputChanges) {
761 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
762 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
763 LaTeXFeatures::isAvailable("xcolor");
765 if (!dvipost && !xcolorulem) {
766 Alert::warning(_("Changes not shown in LaTeX output"),
767 _("Changes will not be highlighted in LaTeX output, "
768 "because neither dvipost nor xcolor/ulem are installed.\n"
769 "Please install these packages or redefine "
770 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
771 } else if (!xcolorulem) {
772 Alert::warning(_("Changes not shown in LaTeX output"),
773 _("Changes will not be highlighted in LaTeX output "
774 "when using pdflatex, because xcolor and ulem are not installed.\n"
775 "Please install both packages or redefine "
776 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
780 if (!params().master.empty()) {
781 FileName const master_file = makeAbsPath(params().master,
782 onlyPath(absFileName()));
783 if (isLyXFileName(master_file.absFileName())) {
785 checkAndLoadLyXFile(master_file, true);
787 // necessary e.g. after a reload
788 // to re-register the child (bug 5873)
789 // FIXME: clean up updateMacros (here, only
790 // child registering is needed).
791 master->updateMacros();
792 // set master as master buffer, but only
793 // if we are a real child
794 if (master->isChild(this))
796 // if the master is not fully loaded
797 // it is probably just loading this
798 // child. No warning needed then.
799 else if (master->isFullyLoaded())
800 LYXERR0("The master '"
802 << "' assigned to this document ("
804 << ") does not include "
805 "this document. Ignoring the master assignment.");
810 // assure we have a default index
811 params().indiceslist().addDefault(B_("Index"));
814 bool const res = text().read(lex, errorList, d->inset);
818 updateMacroInstances();
823 bool Buffer::readString(string const & s)
825 params().compressed = false;
827 // remove dummy empty par
828 paragraphs().clear();
832 FileName const name = FileName::tempName("Buffer_readString");
833 switch (readFile(lex, name, true)) {
837 // We need to call lyx2lyx, so write the input to a file
838 ofstream os(name.toFilesystemEncoding().c_str());
841 return readFile(name);
851 bool Buffer::readFile(FileName const & filename)
853 FileName fname(filename);
855 params().compressed = fname.isZippedFile();
857 // remove dummy empty par
858 paragraphs().clear();
861 if (readFile(lex, fname) != success)
868 bool Buffer::isFullyLoaded() const
870 return d->file_fully_loaded;
874 void Buffer::setFullyLoaded(bool value)
876 d->file_fully_loaded = value;
880 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
883 LASSERT(!filename.empty(), /**/);
885 // the first (non-comment) token _must_ be...
886 if (!lex.checkFor("\\lyxformat")) {
887 Alert::error(_("Document format failure"),
888 bformat(_("%1$s is not a readable LyX document."),
889 from_utf8(filename.absFileName())));
895 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
896 // if present remove ".," from string.
897 size_t dot = tmp_format.find_first_of(".,");
898 //lyxerr << " dot found at " << dot << endl;
899 if (dot != string::npos)
900 tmp_format.erase(dot, 1);
901 int const file_format = convert<int>(tmp_format);
902 //lyxerr << "format: " << file_format << endl;
904 // save timestamp and checksum of the original disk file, making sure
905 // to not overwrite them with those of the file created in the tempdir
906 // when it has to be converted to the current format.
908 // Save the timestamp and checksum of disk file. If filename is an
909 // emergency file, save the timestamp and checksum of the original lyx file
910 // because isExternallyModified will check for this file. (BUG4193)
911 string diskfile = filename.absFileName();
912 if (suffixIs(diskfile, ".emergency"))
913 diskfile = diskfile.substr(0, diskfile.size() - 10);
914 saveCheckSum(FileName(diskfile));
917 if (file_format != LYX_FORMAT) {
920 // lyx2lyx would fail
923 FileName const tmpfile = FileName::tempName("Buffer_readFile");
924 if (tmpfile.empty()) {
925 Alert::error(_("Conversion failed"),
926 bformat(_("%1$s is from a different"
927 " version of LyX, but a temporary"
928 " file for converting it could"
930 from_utf8(filename.absFileName())));
933 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
934 if (lyx2lyx.empty()) {
935 Alert::error(_("Conversion script not found"),
936 bformat(_("%1$s is from a different"
937 " version of LyX, but the"
938 " conversion script lyx2lyx"
939 " could not be found."),
940 from_utf8(filename.absFileName())));
943 ostringstream command;
944 command << os::python()
945 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
946 << " -t " << convert<string>(LYX_FORMAT)
947 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
948 << ' ' << quoteName(filename.toSafeFilesystemEncoding());
949 string const command_str = command.str();
951 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
953 cmd_ret const ret = runCommand(command_str);
954 if (ret.first != 0) {
955 if (file_format < LYX_FORMAT)
956 Alert::error(_("Conversion script failed"),
957 bformat(_("%1$s is from an older version"
958 " of LyX, but the lyx2lyx script"
959 " failed to convert it."),
960 from_utf8(filename.absFileName())));
962 Alert::error(_("Conversion script failed"),
963 bformat(_("%1$s is from a newer version"
964 " of LyX and cannot be converted by the"
966 from_utf8(filename.absFileName())));
969 bool const ret = readFile(tmpfile);
970 // Do stuff with tmpfile name and buffer name here.
971 return ret ? success : failure;
976 if (readDocument(lex)) {
977 Alert::error(_("Document format failure"),
978 bformat(_("%1$s ended unexpectedly, which means"
979 " that it is probably corrupted."),
980 from_utf8(filename.absFileName())));
984 d->file_fully_loaded = true;
989 // Should probably be moved to somewhere else: BufferView? GuiView?
990 bool Buffer::save() const
992 // ask if the disk file has been externally modified (use checksum method)
993 if (fileName().exists() && isExternallyModified(checksum_method)) {
994 docstring const file = makeDisplayPath(absFileName(), 20);
995 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
996 "you want to overwrite this file?"), file);
997 int const ret = Alert::prompt(_("Overwrite modified file?"),
998 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1003 // We don't need autosaves in the immediate future. (Asger)
1004 resetAutosaveTimers();
1006 FileName backupName;
1007 bool madeBackup = false;
1009 // make a backup if the file already exists
1010 if (lyxrc.make_backup && fileName().exists()) {
1011 backupName = FileName(absFileName() + '~');
1012 if (!lyxrc.backupdir_path.empty()) {
1013 string const mangledName =
1014 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1015 backupName = FileName(addName(lyxrc.backupdir_path,
1018 // do not copy because of #6587
1019 if (fileName().moveTo(backupName)) {
1022 Alert::error(_("Backup failure"),
1023 bformat(_("Cannot create backup file %1$s.\n"
1024 "Please check whether the directory exists and is writeable."),
1025 from_utf8(backupName.absFileName())));
1026 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1030 if (writeFile(d->filename)) {
1034 // Saving failed, so backup is not backup
1036 backupName.moveTo(d->filename);
1042 bool Buffer::writeFile(FileName const & fname) const
1044 if (d->read_only && fname == d->filename)
1047 bool retval = false;
1049 docstring const str = bformat(_("Saving document %1$s..."),
1050 makeDisplayPath(fname.absFileName()));
1053 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1055 if (params().compressed) {
1056 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1057 retval = ofs && write(ofs);
1059 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1060 retval = ofs && write(ofs);
1064 message(str + _(" could not write file!"));
1069 // removeAutosaveFile();
1071 saveCheckSum(d->filename);
1072 message(str + _(" done."));
1078 docstring Buffer::emergencyWrite()
1080 // No need to save if the buffer has not changed.
1084 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1086 docstring user_message = bformat(
1087 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1089 // We try to save three places:
1090 // 1) Same place as document. Unless it is an unnamed doc.
1092 string s = absFileName();
1095 if (writeFile(FileName(s))) {
1097 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1098 return user_message;
1100 user_message += _(" Save failed! Trying again...\n");
1104 // 2) In HOME directory.
1105 string s = addName(package().home_dir().absFileName(), absFileName());
1107 lyxerr << ' ' << s << endl;
1108 if (writeFile(FileName(s))) {
1110 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1111 return user_message;
1114 user_message += _(" Save failed! Trying yet again...\n");
1116 // 3) In "/tmp" directory.
1117 // MakeAbsPath to prepend the current
1118 // drive letter on OS/2
1119 s = addName(package().temp_dir().absFileName(), absFileName());
1121 lyxerr << ' ' << s << endl;
1122 if (writeFile(FileName(s))) {
1124 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1125 return user_message;
1128 user_message += _(" Save failed! Bummer. Document is lost.");
1131 return user_message;
1135 bool Buffer::write(ostream & ofs) const
1138 // Use the standard "C" locale for file output.
1139 ofs.imbue(locale::classic());
1142 // The top of the file should not be written by params().
1144 // write out a comment in the top of the file
1145 ofs << "#LyX " << lyx_version
1146 << " created this file. For more info see http://www.lyx.org/\n"
1147 << "\\lyxformat " << LYX_FORMAT << "\n"
1148 << "\\begin_document\n";
1150 /// For each author, set 'used' to true if there is a change
1151 /// by this author in the document; otherwise set it to 'false'.
1152 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1153 AuthorList::Authors::const_iterator a_end = params().authors().end();
1154 for (; a_it != a_end; ++a_it)
1155 a_it->setUsed(false);
1157 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1158 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1159 for ( ; it != end; ++it)
1160 it->checkAuthors(params().authors());
1162 // now write out the buffer parameters.
1163 ofs << "\\begin_header\n";
1164 params().writeFile(ofs);
1165 ofs << "\\end_header\n";
1168 ofs << "\n\\begin_body\n";
1170 ofs << "\n\\end_body\n";
1172 // Write marker that shows file is complete
1173 ofs << "\\end_document" << endl;
1175 // Shouldn't really be needed....
1178 // how to check if close went ok?
1179 // Following is an attempt... (BE 20001011)
1181 // good() returns false if any error occured, including some
1182 // formatting error.
1183 // bad() returns true if something bad happened in the buffer,
1184 // which should include file system full errors.
1189 lyxerr << "File was not closed properly." << endl;
1196 bool Buffer::makeLaTeXFile(FileName const & fname,
1197 string const & original_path,
1198 OutputParams const & runparams_in,
1199 bool output_preamble, bool output_body) const
1201 OutputParams runparams = runparams_in;
1202 if (params().useXetex)
1203 runparams.flavor = OutputParams::XETEX;
1205 string const encoding = runparams.encoding->iconvName();
1206 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1209 try { ofs.reset(encoding); }
1210 catch (iconv_codecvt_facet_exception & e) {
1211 lyxerr << "Caught iconv exception: " << e.what() << endl;
1212 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1213 "verify that the support software for your encoding (%1$s) is "
1214 "properly installed"), from_ascii(encoding)));
1217 if (!openFileWrite(ofs, fname))
1220 //TexStream ts(ofs.rdbuf(), &texrow());
1221 ErrorList & errorList = d->errorLists["Export"];
1223 bool failed_export = false;
1226 writeLaTeXSource(ofs, original_path,
1227 runparams, output_preamble, output_body);
1229 catch (EncodingException & e) {
1230 odocstringstream ods;
1231 ods.put(e.failed_char);
1233 oss << "0x" << hex << e.failed_char << dec;
1234 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1235 " (code point %2$s)"),
1236 ods.str(), from_utf8(oss.str()));
1237 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1238 "representable in the chosen encoding.\n"
1239 "Changing the document encoding to utf8 could help."),
1240 e.par_id, e.pos, e.pos + 1));
1241 failed_export = true;
1243 catch (iconv_codecvt_facet_exception & e) {
1244 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1245 _(e.what()), -1, 0, 0));
1246 failed_export = true;
1248 catch (exception const & e) {
1249 errorList.push_back(ErrorItem(_("conversion failed"),
1250 _(e.what()), -1, 0, 0));
1251 failed_export = true;
1254 lyxerr << "Caught some really weird exception..." << endl;
1260 failed_export = true;
1261 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1265 return !failed_export;
1269 void Buffer::writeLaTeXSource(odocstream & os,
1270 string const & original_path,
1271 OutputParams const & runparams_in,
1272 bool const output_preamble, bool const output_body) const
1274 // The child documents, if any, shall be already loaded at this point.
1276 OutputParams runparams = runparams_in;
1278 // Classify the unicode characters appearing in math insets
1279 Encodings::initUnicodeMath(*this);
1281 // validate the buffer.
1282 LYXERR(Debug::LATEX, " Validating buffer...");
1283 LaTeXFeatures features(*this, params(), runparams);
1285 LYXERR(Debug::LATEX, " Buffer validation done.");
1287 // The starting paragraph of the coming rows is the
1288 // first paragraph of the document. (Asger)
1289 if (output_preamble && runparams.nice) {
1290 os << "%% LyX " << lyx_version << " created this file. "
1291 "For more info, see http://www.lyx.org/.\n"
1292 "%% Do not edit unless you really know what "
1294 d->texrow.newline();
1295 d->texrow.newline();
1297 LYXERR(Debug::INFO, "lyx document header finished");
1299 // Don't move this behind the parent_buffer=0 code below,
1300 // because then the macros will not get the right "redefinition"
1301 // flag as they don't see the parent macros which are output before.
1304 // fold macros if possible, still with parent buffer as the
1305 // macros will be put in the prefix anyway.
1306 updateMacroInstances();
1308 // There are a few differences between nice LaTeX and usual files:
1309 // usual is \batchmode and has a
1310 // special input@path to allow the including of figures
1311 // with either \input or \includegraphics (what figinsets do).
1312 // input@path is set when the actual parameter
1313 // original_path is set. This is done for usual tex-file, but not
1314 // for nice-latex-file. (Matthias 250696)
1315 // Note that input@path is only needed for something the user does
1316 // in the preamble, included .tex files or ERT, files included by
1317 // LyX work without it.
1318 if (output_preamble) {
1319 if (!runparams.nice) {
1320 // code for usual, NOT nice-latex-file
1321 os << "\\batchmode\n"; // changed
1322 // from \nonstopmode
1323 d->texrow.newline();
1325 if (!original_path.empty()) {
1327 // We don't know the encoding of inputpath
1328 docstring const inputpath = from_utf8(support::latex_path(original_path));
1329 docstring uncodable_glyphs;
1330 Encoding const * const enc = runparams.encoding;
1332 for (size_t n = 0; n < inputpath.size(); ++n) {
1333 docstring const glyph =
1334 docstring(1, inputpath[n]);
1335 if (enc->latexChar(inputpath[n], true) != glyph) {
1336 LYXERR0("Uncodable character '"
1338 << "' in input path!");
1339 uncodable_glyphs += glyph;
1344 // warn user if we found uncodable glyphs.
1345 if (!uncodable_glyphs.empty()) {
1346 frontend::Alert::warning(_("Uncodable character in file path"),
1347 support::bformat(_("The path of your document\n"
1349 "contains glyphs that are unknown in the\n"
1350 "current document encoding (namely %2$s).\n"
1351 "This will likely result in incomplete output.\n\n"
1352 "Choose an appropriate document encoding (such as utf8)\n"
1353 "or change the file path name."), inputpath, uncodable_glyphs));
1355 os << "\\makeatletter\n"
1356 << "\\def\\input@path{{"
1357 << inputpath << "/}}\n"
1358 << "\\makeatother\n";
1359 d->texrow.newline();
1360 d->texrow.newline();
1361 d->texrow.newline();
1365 // get parent macros (if this buffer has a parent) which will be
1366 // written at the document begin further down.
1367 MacroSet parentMacros;
1368 listParentMacros(parentMacros, features);
1370 // Write the preamble
1371 runparams.use_babel = params().writeLaTeX(os, features,
1373 d->filename.onlyPath());
1375 runparams.use_japanese = features.isRequired("japanese");
1381 os << "\\begin{document}\n";
1382 d->texrow.newline();
1384 // output the parent macros
1385 MacroSet::iterator it = parentMacros.begin();
1386 MacroSet::iterator end = parentMacros.end();
1387 for (; it != end; ++it) {
1388 int num_lines = (*it)->write(os, true);
1389 d->texrow.newlines(num_lines);
1392 } // output_preamble
1394 d->texrow.start(paragraphs().begin()->id(), 0);
1396 LYXERR(Debug::INFO, "preamble finished, now the body.");
1398 // if we are doing a real file with body, even if this is the
1399 // child of some other buffer, let's cut the link here.
1400 // This happens for example if only a child document is printed.
1401 Buffer const * save_parent = 0;
1402 if (output_preamble) {
1403 save_parent = d->parent();
1408 latexParagraphs(*this, text(), os, d->texrow, runparams);
1410 // Restore the parenthood if needed
1411 if (output_preamble)
1412 d->setParent(save_parent);
1414 // add this just in case after all the paragraphs
1416 d->texrow.newline();
1418 if (output_preamble) {
1419 os << "\\end{document}\n";
1420 d->texrow.newline();
1421 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1423 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1425 runparams_in.encoding = runparams.encoding;
1427 // Just to be sure. (Asger)
1428 d->texrow.newline();
1430 //for (int i = 0; i<d->texrow.rows(); i++) {
1432 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1433 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1436 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1437 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1441 bool Buffer::isLatex() const
1443 return params().documentClass().outputType() == LATEX;
1447 bool Buffer::isLiterate() const
1449 return params().documentClass().outputType() == LITERATE;
1453 bool Buffer::isDocBook() const
1455 return params().documentClass().outputType() == DOCBOOK;
1459 void Buffer::makeDocBookFile(FileName const & fname,
1460 OutputParams const & runparams,
1461 bool const body_only) const
1463 LYXERR(Debug::LATEX, "makeDocBookFile...");
1466 if (!openFileWrite(ofs, fname))
1469 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1473 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1477 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1478 OutputParams const & runparams,
1479 bool const only_body) const
1481 LaTeXFeatures features(*this, params(), runparams);
1486 DocumentClass const & tclass = params().documentClass();
1487 string const top_element = tclass.latexname();
1490 if (runparams.flavor == OutputParams::XML)
1491 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1494 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1497 if (! tclass.class_header().empty())
1498 os << from_ascii(tclass.class_header());
1499 else if (runparams.flavor == OutputParams::XML)
1500 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1501 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1503 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1505 docstring preamble = from_utf8(params().preamble);
1506 if (runparams.flavor != OutputParams::XML ) {
1507 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1508 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1509 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1510 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1513 string const name = runparams.nice
1514 ? changeExtension(absFileName(), ".sgml") : fname;
1515 preamble += features.getIncludedFiles(name);
1516 preamble += features.getLyXSGMLEntities();
1518 if (!preamble.empty()) {
1519 os << "\n [ " << preamble << " ]";
1524 string top = top_element;
1526 if (runparams.flavor == OutputParams::XML)
1527 top += params().language->code();
1529 top += params().language->code().substr(0, 2);
1532 if (!params().options.empty()) {
1534 top += params().options;
1537 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1538 << " file was created by LyX " << lyx_version
1539 << "\n See http://www.lyx.org/ for more information -->\n";
1541 params().documentClass().counters().reset();
1545 sgml::openTag(os, top);
1547 docbookParagraphs(text(), *this, os, runparams);
1548 sgml::closeTag(os, top_element);
1552 void Buffer::makeLyXHTMLFile(FileName const & fname,
1553 OutputParams const & runparams,
1554 bool const body_only) const
1556 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1559 if (!openFileWrite(ofs, fname))
1562 writeLyXHTMLSource(ofs, runparams, body_only);
1566 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1570 void Buffer::writeLyXHTMLSource(odocstream & os,
1571 OutputParams const & runparams,
1572 bool const only_body) const
1574 LaTeXFeatures features(*this, params(), runparams);
1576 updateBuffer(UpdateMaster, OutputUpdate);
1577 checkBibInfoCache();
1578 d->bibinfo_.makeCitationLabels(*this);
1580 updateMacroInstances();
1583 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1584 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n"
1585 // FIXME Language should be set properly.
1586 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1588 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1589 // FIXME Presumably need to set this right
1590 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1592 docstring const & doctitle = features.htmlTitle();
1594 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1597 os << "\n<!-- Text Class Preamble -->\n"
1598 << features.getTClassHTMLPreamble()
1599 << "\n<!-- Premable Snippets -->\n"
1600 << from_utf8(features.getPreambleSnippets());
1602 os << "\n<!-- Layout-provided Styles -->\n";
1603 docstring const styleinfo = features.getTClassHTMLStyles();
1604 if (!styleinfo.empty()) {
1605 os << "<style type='text/css'>\n"
1609 os << "</head>\n<body>\n";
1613 params().documentClass().counters().reset();
1614 xhtmlParagraphs(text(), *this, xs, runparams);
1616 os << "</body>\n</html>\n";
1620 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1621 // Other flags: -wall -v0 -x
1622 int Buffer::runChktex()
1626 // get LaTeX-Filename
1627 FileName const path(temppath());
1628 string const name = addName(path.absFileName(), latexName());
1629 string const org_path = filePath();
1631 PathChanger p(path); // path to LaTeX file
1632 message(_("Running chktex..."));
1634 // Generate the LaTeX file if neccessary
1635 OutputParams runparams(¶ms().encoding());
1636 runparams.flavor = OutputParams::LATEX;
1637 runparams.nice = false;
1638 runparams.linelen = lyxrc.plaintext_linelen;
1639 makeLaTeXFile(FileName(name), org_path, runparams);
1642 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1643 int const res = chktex.run(terr); // run chktex
1646 Alert::error(_("chktex failure"),
1647 _("Could not run chktex successfully."));
1648 } else if (res > 0) {
1649 ErrorList & errlist = d->errorLists["ChkTeX"];
1651 bufferErrors(terr, errlist);
1662 void Buffer::validate(LaTeXFeatures & features) const
1664 params().validate(features);
1668 for_each(paragraphs().begin(), paragraphs().end(),
1669 bind(&Paragraph::validate, _1, ref(features)));
1671 if (lyxerr.debugging(Debug::LATEX)) {
1672 features.showStruct();
1677 void Buffer::getLabelList(vector<docstring> & list) const
1679 // If this is a child document, use the parent's list instead.
1680 Buffer const * const pbuf = d->parent();
1682 pbuf->getLabelList(list);
1687 Toc & toc = d->toc_backend.toc("label");
1688 TocIterator toc_it = toc.begin();
1689 TocIterator end = toc.end();
1690 for (; toc_it != end; ++toc_it) {
1691 if (toc_it->depth() == 0)
1692 list.push_back(toc_it->str());
1697 void Buffer::updateBibfilesCache(UpdateScope scope) const
1699 // If this is a child document, use the parent's cache instead.
1700 Buffer const * const pbuf = d->parent();
1701 if (pbuf && scope != UpdateChildOnly) {
1702 pbuf->updateBibfilesCache();
1706 d->bibfiles_cache_.clear();
1707 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1708 if (it->lyxCode() == BIBTEX_CODE) {
1709 InsetBibtex const & inset =
1710 static_cast<InsetBibtex const &>(*it);
1711 support::FileNameList const bibfiles = inset.getBibFiles();
1712 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1715 } else if (it->lyxCode() == INCLUDE_CODE) {
1716 InsetInclude & inset =
1717 static_cast<InsetInclude &>(*it);
1718 inset.updateBibfilesCache();
1719 support::FileNameList const & bibfiles =
1720 inset.getBibfilesCache();
1721 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1726 // the bibinfo cache is now invalid
1727 d->bibinfo_cache_valid_ = false;
1731 void Buffer::invalidateBibinfoCache()
1733 d->bibinfo_cache_valid_ = false;
1737 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1739 // If this is a child document, use the parent's cache instead.
1740 Buffer const * const pbuf = d->parent();
1741 if (pbuf && scope != UpdateChildOnly)
1742 return pbuf->getBibfilesCache();
1744 // We update the cache when first used instead of at loading time.
1745 if (d->bibfiles_cache_.empty())
1746 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1748 return d->bibfiles_cache_;
1752 BiblioInfo const & Buffer::masterBibInfo() const
1754 // if this is a child document and the parent is already loaded
1755 // use the parent's list instead [ale990412]
1756 Buffer const * const tmp = masterBuffer();
1759 return tmp->masterBibInfo();
1760 return localBibInfo();
1764 BiblioInfo const & Buffer::localBibInfo() const
1770 void Buffer::checkBibInfoCache() const
1772 support::FileNameList const & bibfilesCache = getBibfilesCache();
1773 // compare the cached timestamps with the actual ones.
1774 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1775 support::FileNameList::const_iterator en = bibfilesCache.end();
1776 for (; ei != en; ++ ei) {
1777 time_t lastw = ei->lastModified();
1778 time_t prevw = d->bibfile_status_[*ei];
1779 if (lastw != prevw) {
1780 d->bibinfo_cache_valid_ = false;
1781 d->bibfile_status_[*ei] = lastw;
1785 if (!d->bibinfo_cache_valid_) {
1786 d->bibinfo_.clear();
1787 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1788 it->fillWithBibKeys(d->bibinfo_, it);
1789 d->bibinfo_cache_valid_ = true;
1794 bool Buffer::isDepClean(string const & name) const
1796 DepClean::const_iterator const it = d->dep_clean.find(name);
1797 if (it == d->dep_clean.end())
1803 void Buffer::markDepClean(string const & name)
1805 d->dep_clean[name] = true;
1809 bool Buffer::isExportableFormat(string const & format) const
1811 typedef vector<Format const *> Formats;
1813 formats = exportableFormats(true);
1814 Formats::const_iterator fit = formats.begin();
1815 Formats::const_iterator end = formats.end();
1816 for (; fit != end ; ++fit) {
1817 if ((*fit)->name() == format)
1824 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1827 // FIXME? if there is an Buffer LFUN that can be dispatched even
1828 // if internal, put a switch '(cmd.action)' here.
1834 switch (cmd.action()) {
1836 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1837 flag.setOnOff(isReadonly());
1840 // FIXME: There is need for a command-line import.
1841 //case LFUN_BUFFER_IMPORT:
1843 case LFUN_BUFFER_AUTO_SAVE:
1846 case LFUN_BUFFER_EXPORT_CUSTOM:
1847 // FIXME: Nothing to check here?
1850 case LFUN_BUFFER_EXPORT: {
1851 docstring const arg = cmd.argument();
1852 enable = arg == "custom" || isExportable(to_utf8(arg));
1854 flag.message(bformat(
1855 _("Don't know how to export to format: %1$s"), arg));
1859 case LFUN_BUFFER_CHKTEX:
1860 enable = isLatex() && !lyxrc.chktex_command.empty();
1863 case LFUN_BUILD_PROGRAM:
1864 enable = isExportable("program");
1867 case LFUN_BRANCH_ACTIVATE:
1868 case LFUN_BRANCH_DEACTIVATE: {
1869 BranchList const & branchList = params().branchlist();
1870 docstring const branchName = cmd.argument();
1871 enable = !branchName.empty() && branchList.find(branchName);
1875 case LFUN_BRANCH_ADD:
1876 case LFUN_BRANCHES_RENAME:
1877 case LFUN_BUFFER_PRINT:
1878 // if no Buffer is present, then of course we won't be called!
1881 case LFUN_BUFFER_LANGUAGE:
1882 enable = !isReadonly();
1888 flag.setEnabled(enable);
1893 void Buffer::dispatch(string const & command, DispatchResult & result)
1895 return dispatch(lyxaction.lookupFunc(command), result);
1899 // NOTE We can end up here even if we have no GUI, because we are called
1900 // by LyX::exec to handled command-line requests. So we may need to check
1901 // whether we have a GUI or not. The boolean use_gui holds this information.
1902 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1905 // FIXME? if there is an Buffer LFUN that can be dispatched even
1906 // if internal, put a switch '(cmd.action())' here.
1907 dr.dispatched(false);
1910 string const argument = to_utf8(func.argument());
1911 // We'll set this back to false if need be.
1912 bool dispatched = true;
1913 undo().beginUndoGroup();
1915 switch (func.action()) {
1916 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1917 if (lyxvc().inUse())
1918 lyxvc().toggleReadOnly();
1920 setReadonly(!isReadonly());
1923 case LFUN_BUFFER_EXPORT: {
1924 bool success = doExport(argument, false, false);
1925 dr.setError(!success);
1927 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1932 case LFUN_BUILD_PROGRAM:
1933 doExport("program", true, false);
1936 case LFUN_BUFFER_CHKTEX:
1940 case LFUN_BUFFER_EXPORT_CUSTOM: {
1942 string command = split(argument, format_name, ' ');
1943 Format const * format = formats.getFormat(format_name);
1945 lyxerr << "Format \"" << format_name
1946 << "\" not recognized!"
1951 // The name of the file created by the conversion process
1954 // Output to filename
1955 if (format->name() == "lyx") {
1956 string const latexname = latexName(false);
1957 filename = changeExtension(latexname,
1958 format->extension());
1959 filename = addName(temppath(), filename);
1961 if (!writeFile(FileName(filename)))
1965 doExport(format_name, true, false, filename);
1968 // Substitute $$FName for filename
1969 if (!contains(command, "$$FName"))
1970 command = "( " + command + " ) < $$FName";
1971 command = subst(command, "$$FName", filename);
1973 // Execute the command in the background
1975 call.startscript(Systemcall::DontWait, command);
1979 // FIXME: There is need for a command-line import.
1981 case LFUN_BUFFER_IMPORT:
1986 case LFUN_BUFFER_AUTO_SAVE:
1990 case LFUN_BRANCH_ADD: {
1991 docstring branch_name = func.argument();
1992 if (branch_name.empty()) {
1996 BranchList & branch_list = params().branchlist();
1997 vector<docstring> const branches =
1998 getVectorFromString(branch_name, branch_list.separator());
2000 for (vector<docstring>::const_iterator it = branches.begin();
2001 it != branches.end(); ++it) {
2003 Branch * branch = branch_list.find(branch_name);
2005 LYXERR0("Branch " << branch_name << " already exists.");
2009 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2011 branch_list.add(branch_name);
2012 branch = branch_list.find(branch_name);
2013 string const x11hexname = X11hexname(branch->color());
2014 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2015 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2017 dr.update(Update::Force);
2025 case LFUN_BRANCH_ACTIVATE:
2026 case LFUN_BRANCH_DEACTIVATE: {
2027 BranchList & branchList = params().branchlist();
2028 docstring const branchName = func.argument();
2029 // the case without a branch name is handled elsewhere
2030 if (branchName.empty()) {
2034 Branch * branch = branchList.find(branchName);
2036 LYXERR0("Branch " << branchName << " does not exist.");
2038 docstring const msg =
2039 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2042 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2044 dr.update(Update::Force);
2045 dr.forceBufferUpdate();
2050 case LFUN_BRANCHES_RENAME: {
2051 if (func.argument().empty())
2054 docstring const oldname = from_utf8(func.getArg(0));
2055 docstring const newname = from_utf8(func.getArg(1));
2056 InsetIterator it = inset_iterator_begin(inset());
2057 InsetIterator const end = inset_iterator_end(inset());
2058 bool success = false;
2059 for (; it != end; ++it) {
2060 if (it->lyxCode() == BRANCH_CODE) {
2061 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2062 if (ins.branch() == oldname) {
2063 undo().recordUndo(it);
2064 ins.rename(newname);
2069 if (it->lyxCode() == INCLUDE_CODE) {
2070 // get buffer of external file
2071 InsetInclude const & ins =
2072 static_cast<InsetInclude const &>(*it);
2073 Buffer * child = ins.getChildBuffer();
2076 child->dispatch(func, dr);
2081 dr.update(Update::Force);
2082 dr.forceBufferUpdate();
2087 case LFUN_BUFFER_PRINT: {
2088 // we'll assume there's a problem until we succeed
2090 string target = func.getArg(0);
2091 string target_name = func.getArg(1);
2092 string command = func.getArg(2);
2095 || target_name.empty()
2096 || command.empty()) {
2097 LYXERR0("Unable to parse " << func.argument());
2098 docstring const msg =
2099 bformat(_("Unable to parse \"%1$s\""), func.argument());
2103 if (target != "printer" && target != "file") {
2104 LYXERR0("Unrecognized target \"" << target << '"');
2105 docstring const msg =
2106 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2111 bool const update_unincluded =
2112 params().maintain_unincluded_children
2113 && !params().getIncludedChildren().empty();
2114 if (!doExport("dvi", true, update_unincluded)) {
2115 showPrintError(absFileName());
2116 dr.setMessage(_("Error exporting to DVI."));
2120 // Push directory path.
2121 string const path = temppath();
2122 // Prevent the compiler from optimizing away p
2126 // there are three cases here:
2127 // 1. we print to a file
2128 // 2. we print directly to a printer
2129 // 3. we print using a spool command (print to file first)
2132 string const dviname = changeExtension(latexName(true), "dvi");
2134 if (target == "printer") {
2135 if (!lyxrc.print_spool_command.empty()) {
2136 // case 3: print using a spool
2137 string const psname = changeExtension(dviname,".ps");
2138 command += ' ' + lyxrc.print_to_file
2141 + quoteName(dviname);
2143 string command2 = lyxrc.print_spool_command + ' ';
2144 if (target_name != "default") {
2145 command2 += lyxrc.print_spool_printerprefix
2149 command2 += quoteName(psname);
2151 // If successful, then spool command
2152 res = one.startscript(Systemcall::Wait, command);
2155 // If there's no GUI, we have to wait on this command. Otherwise,
2156 // LyX deletes the temporary directory, and with it the spooled
2157 // file, before it can be printed!!
2158 Systemcall::Starttype stype = use_gui ?
2159 Systemcall::DontWait : Systemcall::Wait;
2160 res = one.startscript(stype, command2);
2163 // case 2: print directly to a printer
2164 if (target_name != "default")
2165 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2167 Systemcall::Starttype stype = use_gui ?
2168 Systemcall::DontWait : Systemcall::Wait;
2169 res = one.startscript(stype, command + quoteName(dviname));
2173 // case 1: print to a file
2174 FileName const filename(makeAbsPath(target_name, filePath()));
2175 FileName const dvifile(makeAbsPath(dviname, path));
2176 if (filename.exists()) {
2177 docstring text = bformat(
2178 _("The file %1$s already exists.\n\n"
2179 "Do you want to overwrite that file?"),
2180 makeDisplayPath(filename.absFileName()));
2181 if (Alert::prompt(_("Overwrite file?"),
2182 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2185 command += ' ' + lyxrc.print_to_file
2186 + quoteName(filename.toFilesystemEncoding())
2188 + quoteName(dvifile.toFilesystemEncoding());
2190 Systemcall::Starttype stype = use_gui ?
2191 Systemcall::DontWait : Systemcall::Wait;
2192 res = one.startscript(stype, command);
2198 dr.setMessage(_("Error running external commands."));
2199 showPrintError(absFileName());
2204 case LFUN_BUFFER_LANGUAGE: {
2205 Language const * oldL = params().language;
2206 Language const * newL = languages.getLanguage(argument);
2207 if (!newL || oldL == newL)
2209 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2210 changeLanguage(oldL, newL);
2211 dr.forceBufferUpdate();
2220 dr.dispatched(dispatched);
2221 undo().endUndoGroup();
2225 void Buffer::changeLanguage(Language const * from, Language const * to)
2227 LASSERT(from, /**/);
2230 for_each(par_iterator_begin(),
2232 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2236 bool Buffer::isMultiLingual() const
2238 ParConstIterator end = par_iterator_end();
2239 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2240 if (it->isMultiLingual(params()))
2247 std::set<Language const *> Buffer::getLanguages() const
2249 std::set<Language const *> languages;
2250 getLanguages(languages);
2255 void Buffer::getLanguages(std::set<Language const *> & languages) const
2257 ParConstIterator end = par_iterator_end();
2258 // add the buffer language, even if it's not actively used
2259 languages.insert(language());
2260 // iterate over the paragraphs
2261 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2262 it->getLanguages(languages);
2264 std::vector<Buffer *> clist = getChildren();
2265 for (vector<Buffer *>::const_iterator cit = clist.begin();
2266 cit != clist.end(); ++cit)
2267 (*cit)->getLanguages(languages);
2271 DocIterator Buffer::getParFromID(int const id) const
2273 Buffer * buf = const_cast<Buffer *>(this);
2275 // John says this is called with id == -1 from undo
2276 lyxerr << "getParFromID(), id: " << id << endl;
2277 return doc_iterator_end(buf);
2280 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2281 if (it.paragraph().id() == id)
2284 return doc_iterator_end(buf);
2288 bool Buffer::hasParWithID(int const id) const
2290 return !getParFromID(id).atEnd();
2294 ParIterator Buffer::par_iterator_begin()
2296 return ParIterator(doc_iterator_begin(this));
2300 ParIterator Buffer::par_iterator_end()
2302 return ParIterator(doc_iterator_end(this));
2306 ParConstIterator Buffer::par_iterator_begin() const
2308 return ParConstIterator(doc_iterator_begin(this));
2312 ParConstIterator Buffer::par_iterator_end() const
2314 return ParConstIterator(doc_iterator_end(this));
2318 Language const * Buffer::language() const
2320 return params().language;
2324 docstring const Buffer::B_(string const & l10n) const
2326 return params().B_(l10n);
2330 bool Buffer::isClean() const
2332 return d->lyx_clean;
2336 bool Buffer::isExternallyModified(CheckMethod method) const
2338 LASSERT(d->filename.exists(), /**/);
2339 // if method == timestamp, check timestamp before checksum
2340 return (method == checksum_method
2341 || d->timestamp_ != d->filename.lastModified())
2342 && d->checksum_ != d->filename.checksum();
2346 void Buffer::saveCheckSum(FileName const & file) const
2348 if (file.exists()) {
2349 d->timestamp_ = file.lastModified();
2350 d->checksum_ = file.checksum();
2352 // in the case of save to a new file.
2359 void Buffer::markClean() const
2361 if (!d->lyx_clean) {
2362 d->lyx_clean = true;
2365 // if the .lyx file has been saved, we don't need an
2367 d->bak_clean = true;
2371 void Buffer::setUnnamed(bool flag)
2377 bool Buffer::isUnnamed() const
2384 /// Don't check unnamed, here: isInternal() is used in
2385 /// newBuffer(), where the unnamed flag has not been set by anyone
2386 /// yet. Also, for an internal buffer, there should be no need for
2387 /// retrieving fileName() nor for checking if it is unnamed or not.
2388 bool Buffer::isInternal() const
2390 return fileName().extension() == "internal";
2394 void Buffer::markDirty()
2397 d->lyx_clean = false;
2400 d->bak_clean = false;
2402 DepClean::iterator it = d->dep_clean.begin();
2403 DepClean::const_iterator const end = d->dep_clean.end();
2405 for (; it != end; ++it)
2410 FileName Buffer::fileName() const
2416 string Buffer::absFileName() const
2418 return d->filename.absFileName();
2422 string Buffer::filePath() const
2424 return d->filename.onlyPath().absFileName() + "/";
2428 bool Buffer::isReadonly() const
2430 return d->read_only;
2434 void Buffer::setParent(Buffer const * buffer)
2436 // Avoids recursive include.
2437 d->setParent(buffer == this ? 0 : buffer);
2442 Buffer const * Buffer::parent() const
2448 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2450 bufs.insert(owner_);
2452 parent()->d->collectRelatives(bufs);
2454 // loop over children
2455 BufferPositionMap::const_iterator it = children_positions.begin();
2456 BufferPositionMap::const_iterator end = children_positions.end();
2457 for (; it != end; ++it)
2458 bufs.insert(const_cast<Buffer *>(it->first));
2462 std::vector<Buffer const *> Buffer::allRelatives() const
2465 d->collectRelatives(bufs);
2466 BufferSet::iterator it = bufs.begin();
2467 std::vector<Buffer const *> ret;
2468 for (; it != bufs.end(); ++it)
2474 Buffer const * Buffer::masterBuffer() const
2476 Buffer const * const pbuf = d->parent();
2480 return pbuf->masterBuffer();
2484 bool Buffer::isChild(Buffer * child) const
2486 return d->children_positions.find(child) != d->children_positions.end();
2490 DocIterator Buffer::firstChildPosition(Buffer const * child)
2492 Impl::BufferPositionMap::iterator it;
2493 it = d->children_positions.find(child);
2494 if (it == d->children_positions.end())
2495 return DocIterator(this);
2500 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2502 // loop over children
2503 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2504 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2505 for (; it != end; ++it) {
2506 Buffer * child = const_cast<Buffer *>(it->first);
2507 clist.push_back(child);
2508 if (grand_children) {
2509 // there might be grandchildren
2510 vector<Buffer *> glist = child->getChildren();
2511 clist.insert(clist.end(), glist.begin(), glist.end());
2517 vector<Buffer *> Buffer::getChildren(bool grand_children) const
2520 getChildren(v, grand_children);
2525 template<typename M>
2526 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2531 typename M::const_iterator it = m.lower_bound(x);
2532 if (it == m.begin())
2540 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2541 DocIterator const & pos) const
2543 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2545 // if paragraphs have no macro context set, pos will be empty
2549 // we haven't found anything yet
2550 DocIterator bestPos = owner_->par_iterator_begin();
2551 MacroData const * bestData = 0;
2553 // find macro definitions for name
2554 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2555 if (nameIt != macros.end()) {
2556 // find last definition in front of pos or at pos itself
2557 PositionScopeMacroMap::const_iterator it
2558 = greatest_below(nameIt->second, pos);
2559 if (it != nameIt->second.end()) {
2561 // scope ends behind pos?
2562 if (pos < it->second.first) {
2563 // Looks good, remember this. If there
2564 // is no external macro behind this,
2565 // we found the right one already.
2566 bestPos = it->first;
2567 bestData = &it->second.second;
2571 // try previous macro if there is one
2572 if (it == nameIt->second.begin())
2579 // find macros in included files
2580 PositionScopeBufferMap::const_iterator it
2581 = greatest_below(position_to_children, pos);
2582 if (it == position_to_children.end())
2583 // no children before
2587 // do we know something better (i.e. later) already?
2588 if (it->first < bestPos )
2591 // scope ends behind pos?
2592 if (pos < it->second.first) {
2593 // look for macro in external file
2595 MacroData const * data
2596 = it->second.second->getMacro(name, false);
2599 bestPos = it->first;
2605 // try previous file if there is one
2606 if (it == position_to_children.begin())
2611 // return the best macro we have found
2616 MacroData const * Buffer::getMacro(docstring const & name,
2617 DocIterator const & pos, bool global) const
2622 // query buffer macros
2623 MacroData const * data = d->getBufferMacro(name, pos);
2627 // If there is a master buffer, query that
2628 Buffer const * const pbuf = d->parent();
2630 d->macro_lock = true;
2631 MacroData const * macro = pbuf->getMacro(
2632 name, *this, false);
2633 d->macro_lock = false;
2639 data = MacroTable::globalMacros().get(name);
2648 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2650 // set scope end behind the last paragraph
2651 DocIterator scope = par_iterator_begin();
2652 scope.pit() = scope.lastpit() + 1;
2654 return getMacro(name, scope, global);
2658 MacroData const * Buffer::getMacro(docstring const & name,
2659 Buffer const & child, bool global) const
2661 // look where the child buffer is included first
2662 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2663 if (it == d->children_positions.end())
2666 // check for macros at the inclusion position
2667 return getMacro(name, it->second, global);
2671 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope,
2674 pit_type const lastpit = it.lastpit();
2676 // look for macros in each paragraph
2677 while (it.pit() <= lastpit) {
2678 Paragraph & par = it.paragraph();
2680 // iterate over the insets of the current paragraph
2681 InsetList const & insets = par.insetList();
2682 InsetList::const_iterator iit = insets.begin();
2683 InsetList::const_iterator end = insets.end();
2684 for (; iit != end; ++iit) {
2685 it.pos() = iit->pos;
2687 // is it a nested text inset?
2688 if (iit->inset->asInsetText()) {
2689 // Inset needs its own scope?
2690 InsetText const * itext = iit->inset->asInsetText();
2691 bool newScope = itext->isMacroScope();
2693 // scope which ends just behind the inset
2694 DocIterator insetScope = it;
2697 // collect macros in inset
2698 it.push_back(CursorSlice(*iit->inset));
2699 updateMacros(it, newScope ? insetScope : scope);
2704 // is it an external file?
2705 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2706 // get buffer of external file
2707 InsetInclude const & inset =
2708 static_cast<InsetInclude const &>(*iit->inset);
2710 Buffer * child = inset.getChildBuffer();
2715 // register its position, but only when it is
2716 // included first in the buffer
2717 if (children_positions.find(child) ==
2718 children_positions.end())
2719 children_positions[child] = it;
2721 // register child with its scope
2722 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2726 if (record_docits && iit->inset->asInsetMath()) {
2727 InsetMath * im = static_cast<InsetMath *>(iit->inset);
2728 if (im->asHullInset()) {
2729 InsetMathHull * hull = static_cast<InsetMathHull *>(im);
2730 hull->recordLocation(it);
2734 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2738 MathMacroTemplate & macroTemplate =
2739 static_cast<MathMacroTemplate &>(*iit->inset);
2740 MacroContext mc(owner_, it);
2741 macroTemplate.updateToContext(mc);
2744 bool valid = macroTemplate.validMacro();
2745 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2746 // then the BufferView's cursor will be invalid in
2747 // some cases which leads to crashes.
2752 // FIXME (Abdel), I don't understandt why we pass 'it' here
2753 // instead of 'macroTemplate' defined above... is this correct?
2754 macros[macroTemplate.name()][it] =
2755 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2765 void Buffer::updateMacros(bool record_docit) const
2770 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2772 // start with empty table
2774 d->children_positions.clear();
2775 d->position_to_children.clear();
2777 // Iterate over buffer, starting with first paragraph
2778 // The scope must be bigger than any lookup DocIterator
2779 // later. For the global lookup, lastpit+1 is used, hence
2780 // we use lastpit+2 here.
2781 DocIterator it = par_iterator_begin();
2782 DocIterator outerScope = it;
2783 outerScope.pit() = outerScope.lastpit() + 2;
2784 d->updateMacros(it, outerScope, record_docit);
2788 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2790 InsetIterator it = inset_iterator_begin(inset());
2791 InsetIterator const end = inset_iterator_end(inset());
2792 for (; it != end; ++it) {
2793 if (it->lyxCode() == BRANCH_CODE) {
2794 InsetBranch & br = static_cast<InsetBranch &>(*it);
2795 docstring const name = br.branch();
2796 if (!from_master && !params().branchlist().find(name))
2797 result.push_back(name);
2798 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2799 result.push_back(name);
2802 if (it->lyxCode() == INCLUDE_CODE) {
2803 // get buffer of external file
2804 InsetInclude const & ins =
2805 static_cast<InsetInclude const &>(*it);
2806 Buffer * child = ins.getChildBuffer();
2809 child->getUsedBranches(result, true);
2812 // remove duplicates
2817 void Buffer::updateMacroInstances() const
2819 LYXERR(Debug::MACROS, "updateMacroInstances for "
2820 << d->filename.onlyFileName());
2821 DocIterator it = doc_iterator_begin(this);
2823 DocIterator const end = doc_iterator_end(this);
2824 for (; it != end; it.forwardInset()) {
2825 // look for MathData cells in InsetMathNest insets
2826 InsetMath * minset = it.nextInset()->asInsetMath();
2830 // update macro in all cells of the InsetMathNest
2831 DocIterator::idx_type n = minset->nargs();
2832 MacroContext mc = MacroContext(this, it);
2833 for (DocIterator::idx_type i = 0; i < n; ++i) {
2834 MathData & data = minset->cell(i);
2835 data.updateMacros(0, mc);
2841 void Buffer::listMacroNames(MacroNameSet & macros) const
2846 d->macro_lock = true;
2848 // loop over macro names
2849 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2850 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2851 for (; nameIt != nameEnd; ++nameIt)
2852 macros.insert(nameIt->first);
2854 // loop over children
2855 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2856 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2857 for (; it != end; ++it)
2858 it->first->listMacroNames(macros);
2861 Buffer const * const pbuf = d->parent();
2863 pbuf->listMacroNames(macros);
2865 d->macro_lock = false;
2869 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2871 Buffer const * const pbuf = d->parent();
2876 pbuf->listMacroNames(names);
2879 MacroNameSet::iterator it = names.begin();
2880 MacroNameSet::iterator end = names.end();
2881 for (; it != end; ++it) {
2883 MacroData const * data =
2884 pbuf->getMacro(*it, *this, false);
2886 macros.insert(data);
2888 // we cannot access the original MathMacroTemplate anymore
2889 // here to calls validate method. So we do its work here manually.
2890 // FIXME: somehow make the template accessible here.
2891 if (data->optionals() > 0)
2892 features.require("xargs");
2898 Buffer::References & Buffer::references(docstring const & label)
2901 return const_cast<Buffer *>(masterBuffer())->references(label);
2903 RefCache::iterator it = d->ref_cache_.find(label);
2904 if (it != d->ref_cache_.end())
2905 return it->second.second;
2907 static InsetLabel const * dummy_il = 0;
2908 static References const dummy_refs;
2909 it = d->ref_cache_.insert(
2910 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2911 return it->second.second;
2915 Buffer::References const & Buffer::references(docstring const & label) const
2917 return const_cast<Buffer *>(this)->references(label);
2921 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2923 masterBuffer()->d->ref_cache_[label].first = il;
2927 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2929 return masterBuffer()->d->ref_cache_[label].first;
2933 void Buffer::clearReferenceCache() const
2936 d->ref_cache_.clear();
2940 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2943 //FIXME: This does not work for child documents yet.
2944 LASSERT(code == CITE_CODE, /**/);
2945 // Check if the label 'from' appears more than once
2946 vector<docstring> labels;
2948 checkBibInfoCache();
2949 BiblioInfo const & keys = masterBibInfo();
2950 BiblioInfo::const_iterator bit = keys.begin();
2951 BiblioInfo::const_iterator bend = keys.end();
2953 for (; bit != bend; ++bit)
2955 labels.push_back(bit->first);
2958 if (count(labels.begin(), labels.end(), from) > 1)
2961 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2962 if (it->lyxCode() == code) {
2963 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2964 docstring const oldValue = inset.getParam(paramName);
2965 if (oldValue == from)
2966 inset.setParam(paramName, to);
2972 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2973 pit_type par_end, bool full_source) const
2975 OutputParams runparams(¶ms().encoding());
2976 runparams.nice = true;
2977 runparams.flavor = params().useXetex ?
2978 OutputParams::XETEX : OutputParams::LATEX;
2979 runparams.linelen = lyxrc.plaintext_linelen;
2980 // No side effect of file copying and image conversion
2981 runparams.dryrun = true;
2984 os << "% " << _("Preview source code") << "\n\n";
2986 d->texrow.newline();
2987 d->texrow.newline();
2989 writeDocBookSource(os, absFileName(), runparams, false);
2991 // latex or literate
2992 writeLaTeXSource(os, string(), runparams, true, true);
2994 runparams.par_begin = par_begin;
2995 runparams.par_end = par_end;
2996 if (par_begin + 1 == par_end) {
2998 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3002 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3003 convert<docstring>(par_begin),
3004 convert<docstring>(par_end - 1))
3011 // output paragraphs
3013 docbookParagraphs(text(), *this, os, runparams);
3015 // latex or literate
3016 latexParagraphs(*this, text(), os, texrow, runparams);
3021 ErrorList & Buffer::errorList(string const & type) const
3023 static ErrorList emptyErrorList;
3024 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3025 if (it == d->errorLists.end())
3026 return emptyErrorList;
3032 void Buffer::updateTocItem(std::string const & type,
3033 DocIterator const & dit) const
3036 d->gui_->updateTocItem(type, dit);
3040 void Buffer::structureChanged() const
3043 d->gui_->structureChanged();
3047 void Buffer::errors(string const & err, bool from_master) const
3050 d->gui_->errors(err, from_master);
3054 void Buffer::message(docstring const & msg) const
3057 d->gui_->message(msg);
3061 void Buffer::setBusy(bool on) const
3064 d->gui_->setBusy(on);
3068 void Buffer::updateTitles() const
3071 d->wa_->updateTitles();
3075 void Buffer::resetAutosaveTimers() const
3078 d->gui_->resetAutosaveTimers();
3082 bool Buffer::hasGuiDelegate() const
3088 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3097 class AutoSaveBuffer : public ForkedProcess {
3100 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3101 : buffer_(buffer), fname_(fname) {}
3103 virtual shared_ptr<ForkedProcess> clone() const
3105 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3110 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3111 from_utf8(fname_.absFileName())));
3112 return run(DontWait);
3116 virtual int generateChild();
3118 Buffer const & buffer_;
3123 int AutoSaveBuffer::generateChild()
3125 #if defined(__APPLE__)
3126 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3127 * We should use something else like threads.
3129 * Since I do not know how to determine at run time what is the OS X
3130 * version, I just disable forking altogether for now (JMarc)
3132 pid_t const pid = -1;
3134 // tmp_ret will be located (usually) in /tmp
3135 // will that be a problem?
3136 // Note that this calls ForkedCalls::fork(), so it's
3137 // ok cross-platform.
3138 pid_t const pid = fork();
3139 // If you want to debug the autosave
3140 // you should set pid to -1, and comment out the fork.
3141 if (pid != 0 && pid != -1)
3145 // pid = -1 signifies that lyx was unable
3146 // to fork. But we will do the save
3148 bool failed = false;
3149 FileName const tmp_ret = FileName::tempName("lyxauto");
3150 if (!tmp_ret.empty()) {
3151 buffer_.writeFile(tmp_ret);
3152 // assume successful write of tmp_ret
3153 if (!tmp_ret.moveTo(fname_))
3159 // failed to write/rename tmp_ret so try writing direct
3160 if (!buffer_.writeFile(fname_)) {
3161 // It is dangerous to do this in the child,
3162 // but safe in the parent, so...
3163 if (pid == -1) // emit message signal.
3164 buffer_.message(_("Autosave failed!"));
3168 if (pid == 0) // we are the child so...
3177 FileName Buffer::getAutosaveFileName() const
3179 // if the document is unnamed try to save in the backup dir, else
3180 // in the default document path, and as a last try in the filePath,
3181 // which will most often be the temporary directory
3184 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3185 : lyxrc.backupdir_path;
3186 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3189 string const fname = "#" + d->filename.onlyFileName() + "#";
3190 return makeAbsPath(fname, fpath);
3194 void Buffer::removeAutosaveFile() const
3196 FileName const f = getAutosaveFileName();
3202 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3204 FileName const newauto = getAutosaveFileName();
3206 if (newauto != oldauto && oldauto.exists())
3207 if (!oldauto.moveTo(newauto))
3208 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3212 // Perfect target for a thread...
3213 void Buffer::autoSave() const
3215 if (d->bak_clean || isReadonly()) {
3216 // We don't save now, but we'll try again later
3217 resetAutosaveTimers();
3221 // emit message signal.
3222 message(_("Autosaving current document..."));
3223 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3226 d->bak_clean = true;
3228 resetAutosaveTimers();
3232 string Buffer::bufferFormat() const
3234 string format = params().documentClass().outputFormat();
3235 if (format == "latex") {
3236 if (params().useXetex)
3238 if (params().encoding().package() == Encoding::japanese)
3245 string Buffer::getDefaultOutputFormat() const
3247 if (!params().defaultOutputFormat.empty()
3248 && params().defaultOutputFormat != "default")
3249 return params().defaultOutputFormat;
3250 typedef vector<Format const *> Formats;
3251 Formats formats = exportableFormats(true);
3254 || params().useXetex
3255 || params().encoding().package() == Encoding::japanese) {
3256 if (formats.empty())
3258 // return the first we find
3259 return formats.front()->name();
3261 return lyxrc.default_view_format;
3266 // helper class, to guarantee this gets reset properly
3267 class MarkAsExporting {
3269 MarkAsExporting(Buffer const * buf) : buf_(buf)
3271 LASSERT(buf_, /* */);
3272 buf_->setExportStatus(true);
3276 buf_->setExportStatus(false);
3279 Buffer const * const buf_;
3284 void Buffer::setExportStatus(bool e) const
3286 d->doing_export = e;
3290 bool Buffer::isExporting() const
3292 return d->doing_export;
3296 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3297 bool includeall, string & result_file) const
3299 MarkAsExporting exporting(this);
3300 string backend_format;
3301 OutputParams runparams(¶ms().encoding());
3302 runparams.flavor = OutputParams::LATEX;
3303 runparams.linelen = lyxrc.plaintext_linelen;
3304 runparams.includeall = includeall;
3305 vector<string> backs = backends();
3306 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3307 // Get shortest path to format
3308 Graph::EdgePath path;
3309 for (vector<string>::const_iterator it = backs.begin();
3310 it != backs.end(); ++it) {
3311 Graph::EdgePath p = theConverters().getPath(*it, format);
3312 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3313 backend_format = *it;
3318 if (!put_in_tempdir) {
3319 // Only show this alert if this is an export to a non-temporary
3320 // file (not for previewing).
3321 Alert::error(_("Couldn't export file"), bformat(
3322 _("No information for exporting the format %1$s."),
3323 formats.prettyName(format)));
3327 runparams.flavor = theConverters().getFlavor(path);
3330 backend_format = format;
3331 // FIXME: Don't hardcode format names here, but use a flag
3332 if (backend_format == "pdflatex")
3333 runparams.flavor = OutputParams::PDFLATEX;
3336 string filename = latexName(false);
3337 filename = addName(temppath(), filename);
3338 filename = changeExtension(filename,
3339 formats.extension(backend_format));
3342 updateMacroInstances();
3344 // Plain text backend
3345 if (backend_format == "text") {
3346 runparams.flavor = OutputParams::TEXT;
3347 writePlaintextFile(*this, FileName(filename), runparams);
3350 else if (backend_format == "xhtml") {
3351 runparams.flavor = OutputParams::HTML;
3352 switch (params().html_math_output) {
3353 case BufferParams::MathML:
3354 runparams.math_flavor = OutputParams::MathAsMathML;
3356 case BufferParams::HTML:
3357 runparams.math_flavor = OutputParams::MathAsHTML;
3359 case BufferParams::Images:
3360 runparams.math_flavor = OutputParams::MathAsImages;
3362 case BufferParams::LaTeX:
3363 runparams.math_flavor = OutputParams::MathAsLaTeX;
3367 makeLyXHTMLFile(FileName(filename), runparams);
3368 } else if (backend_format == "lyx")
3369 writeFile(FileName(filename));
3371 else if (isDocBook()) {
3372 runparams.nice = !put_in_tempdir;
3373 makeDocBookFile(FileName(filename), runparams);
3376 else if (backend_format == format) {
3377 runparams.nice = true;
3378 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3380 } else if (!lyxrc.tex_allows_spaces
3381 && contains(filePath(), ' ')) {
3382 Alert::error(_("File name error"),
3383 _("The directory path to the document cannot contain spaces."));
3386 runparams.nice = false;
3387 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3391 string const error_type = (format == "program")
3392 ? "Build" : bufferFormat();
3393 ErrorList & error_list = d->errorLists[error_type];
3394 string const ext = formats.extension(format);
3395 FileName const tmp_result_file(changeExtension(filename, ext));
3396 bool const success = theConverters().convert(this, FileName(filename),
3397 tmp_result_file, FileName(absFileName()), backend_format, format,
3400 // Emit the signal to show the error list or copy it back to the
3401 // cloned Buffer so that it cab be emitted afterwards.
3402 if (format != backend_format) {
3403 if (d->cloned_buffer_) {
3404 d->cloned_buffer_->d->errorLists[error_type] =
3405 d->errorLists[error_type];
3408 // also to the children, in case of master-buffer-view
3409 std::vector<Buffer *> clist = getChildren();
3410 for (vector<Buffer *>::const_iterator cit = clist.begin();
3411 cit != clist.end(); ++cit) {
3412 if (d->cloned_buffer_) {
3413 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3414 (*cit)->d->errorLists[error_type];
3416 (*cit)->errors(error_type, true);
3420 if (d->cloned_buffer_) {
3421 // Enable reverse dvi or pdf to work by copying back the texrow
3422 // object to the cloned buffer.
3423 // FIXME: There is a possibility of concurrent access to texrow
3424 // here from the main GUI thread that should be securized.
3425 d->cloned_buffer_->d->texrow = d->texrow;
3426 string const error_type = bufferFormat();
3427 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3433 if (put_in_tempdir) {
3434 result_file = tmp_result_file.absFileName();
3438 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3439 // We need to copy referenced files (e. g. included graphics
3440 // if format == "dvi") to the result dir.
3441 vector<ExportedFile> const files =
3442 runparams.exportdata->externalFiles(format);
3443 string const dest = onlyPath(result_file);
3444 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3445 : force_overwrite == ALL_FILES;
3446 CopyStatus status = use_force ? FORCE : SUCCESS;
3448 vector<ExportedFile>::const_iterator it = files.begin();
3449 vector<ExportedFile>::const_iterator const en = files.end();
3450 for (; it != en && status != CANCEL; ++it) {
3451 string const fmt = formats.getFormatFromFile(it->sourceName);
3452 status = copyFile(fmt, it->sourceName,
3453 makeAbsPath(it->exportName, dest),
3454 it->exportName, status == FORCE);
3457 if (status == CANCEL) {
3458 message(_("Document export cancelled."));
3459 } else if (tmp_result_file.exists()) {
3460 // Finally copy the main file
3461 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3462 : force_overwrite != NO_FILES;
3463 if (status == SUCCESS && use_force)
3465 status = copyFile(format, tmp_result_file,
3466 FileName(result_file), result_file,
3468 message(bformat(_("Document exported as %1$s "
3470 formats.prettyName(format),
3471 makeDisplayPath(result_file)));
3473 // This must be a dummy converter like fax (bug 1888)
3474 message(bformat(_("Document exported as %1$s"),
3475 formats.prettyName(format)));
3482 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3483 bool includeall) const
3486 // (1) export with all included children (omit \includeonly)
3487 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3489 // (2) export with included children only
3490 return doExport(format, put_in_tempdir, false, result_file);
3494 bool Buffer::preview(string const & format, bool includeall) const
3496 MarkAsExporting exporting(this);
3498 // (1) export with all included children (omit \includeonly)
3499 if (includeall && !doExport(format, true, true))
3501 // (2) export with included children only
3502 if (!doExport(format, true, false, result_file))
3504 return formats.view(*this, FileName(result_file), format);
3508 bool Buffer::isExportable(string const & format) const
3510 vector<string> backs = backends();
3511 for (vector<string>::const_iterator it = backs.begin();
3512 it != backs.end(); ++it)
3513 if (theConverters().isReachable(*it, format))
3519 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3521 vector<string> const backs = backends();
3522 vector<Format const *> result =
3523 theConverters().getReachable(backs[0], only_viewable, true);
3524 for (vector<string>::const_iterator it = backs.begin() + 1;
3525 it != backs.end(); ++it) {
3526 vector<Format const *> r =
3527 theConverters().getReachable(*it, only_viewable, false);
3528 result.insert(result.end(), r.begin(), r.end());
3534 vector<string> Buffer::backends() const
3537 v.push_back(bufferFormat());
3538 // FIXME: Don't hardcode format names here, but use a flag
3539 if (v.back() == "latex")
3540 v.push_back("pdflatex");
3541 v.push_back("xhtml");
3542 v.push_back("text");
3548 bool Buffer::readFileHelper(FileName const & s)
3550 // File information about normal file
3552 docstring const file = makeDisplayPath(s.absFileName(), 50);
3553 docstring text = bformat(_("The specified document\n%1$s"
3554 "\ncould not be read."), file);
3555 Alert::error(_("Could not read document"), text);
3559 // Check if emergency save file exists and is newer.
3560 FileName const e(s.absFileName() + ".emergency");
3562 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3563 docstring const file = makeDisplayPath(s.absFileName(), 20);
3564 docstring const text =
3565 bformat(_("An emergency save of the document "
3567 "Recover emergency save?"), file);
3568 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3569 _("&Recover"), _("&Load Original"),
3573 // the file is not saved if we load the emergency file.
3578 if ((res = readFile(e)) == success)
3579 str = _("Document was successfully recovered.");
3581 str = _("Document was NOT successfully recovered.");
3582 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3583 makeDisplayPath(e.absFileName()));
3585 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3586 _("&Remove"), _("&Keep it"))) {
3589 Alert::warning(_("Emergency file deleted"),
3590 _("Do not forget to save your file now!"), true);
3595 if (!Alert::prompt(_("Delete emergency file?"),
3596 _("Remove emergency file now?"), 1, 1,
3597 _("&Remove"), _("&Keep it")))
3605 // Now check if autosave file is newer.
3606 FileName const a(onlyPath(s.absFileName()) + '#' + onlyFileName(s.absFileName()) + '#');
3608 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3609 docstring const file = makeDisplayPath(s.absFileName(), 20);
3610 docstring const text =
3611 bformat(_("The backup of the document "
3612 "%1$s is newer.\n\nLoad the "
3613 "backup instead?"), file);
3614 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3615 _("&Load backup"), _("Load &original"),
3619 // the file is not saved if we load the autosave file.
3623 // Here we delete the autosave
3634 bool Buffer::loadLyXFile(FileName const & s)
3636 // If the file is not readable, we try to
3637 // retrieve the file from version control.
3638 if (!s.isReadableFile()
3639 && !LyXVC::file_not_found_hook(s))
3642 if (s.isReadableFile()){
3643 // InsetInfo needs to know if file is under VCS
3644 lyxvc().file_found_hook(s);
3645 if (readFileHelper(s)) {
3646 d->read_only = !s.isWritable();
3654 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3656 TeXErrors::Errors::const_iterator cit = terr.begin();
3657 TeXErrors::Errors::const_iterator end = terr.end();
3659 for (; cit != end; ++cit) {
3662 int errorRow = cit->error_in_line;
3663 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3669 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3670 } while (found && id_start == id_end && pos_start == pos_end);
3672 errorList.push_back(ErrorItem(cit->error_desc,
3673 cit->error_text, id_start, pos_start, pos_end));
3678 void Buffer::setBuffersForInsets() const
3680 inset().setBuffer(const_cast<Buffer &>(*this));
3684 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3686 // Use the master text class also for child documents
3687 Buffer const * const master = masterBuffer();
3688 DocumentClass const & textclass = master->params().documentClass();
3690 // do this only if we are the top-level Buffer
3691 if (scope != UpdateMaster || master == this)
3692 checkBibInfoCache();
3694 // keep the buffers to be children in this set. If the call from the
3695 // master comes back we can see which of them were actually seen (i.e.
3696 // via an InsetInclude). The remaining ones in the set need still be updated.
3697 static std::set<Buffer const *> bufToUpdate;
3698 if (scope == UpdateMaster) {
3699 // If this is a child document start with the master
3700 if (master != this) {
3701 bufToUpdate.insert(this);
3702 master->updateBuffer(UpdateMaster, utype);
3703 // Do this here in case the master has no gui associated with it. Then,
3704 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3705 if (!master->d->gui_)
3708 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3709 if (bufToUpdate.find(this) == bufToUpdate.end())
3713 // start over the counters in the master
3714 textclass.counters().reset();
3717 // update will be done below for this buffer
3718 bufToUpdate.erase(this);
3720 // update all caches
3721 clearReferenceCache();
3724 Buffer & cbuf = const_cast<Buffer &>(*this);
3726 LASSERT(!text().paragraphs().empty(), /**/);
3729 ParIterator parit = cbuf.par_iterator_begin();
3730 updateBuffer(parit, utype);
3733 // TocBackend update will be done later.
3736 cbuf.tocBackend().update();
3737 if (scope == UpdateMaster)
3738 cbuf.structureChanged();
3742 static depth_type getDepth(DocIterator const & it)
3744 depth_type depth = 0;
3745 for (size_t i = 0 ; i < it.depth() ; ++i)
3746 if (!it[i].inset().inMathed())
3747 depth += it[i].paragraph().getDepth() + 1;
3748 // remove 1 since the outer inset does not count
3752 static depth_type getItemDepth(ParIterator const & it)
3754 Paragraph const & par = *it;
3755 LabelType const labeltype = par.layout().labeltype;
3757 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3760 // this will hold the lowest depth encountered up to now.
3761 depth_type min_depth = getDepth(it);
3762 ParIterator prev_it = it;
3765 --prev_it.top().pit();
3767 // start of nested inset: go to outer par
3769 if (prev_it.empty()) {
3770 // start of document: nothing to do
3775 // We search for the first paragraph with same label
3776 // that is not more deeply nested.
3777 Paragraph & prev_par = *prev_it;
3778 depth_type const prev_depth = getDepth(prev_it);
3779 if (labeltype == prev_par.layout().labeltype) {
3780 if (prev_depth < min_depth)
3781 return prev_par.itemdepth + 1;
3782 if (prev_depth == min_depth)
3783 return prev_par.itemdepth;
3785 min_depth = min(min_depth, prev_depth);
3786 // small optimization: if we are at depth 0, we won't
3787 // find anything else
3788 if (prev_depth == 0)
3794 static bool needEnumCounterReset(ParIterator const & it)
3796 Paragraph const & par = *it;
3797 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3798 depth_type const cur_depth = par.getDepth();
3799 ParIterator prev_it = it;
3800 while (prev_it.pit()) {
3801 --prev_it.top().pit();
3802 Paragraph const & prev_par = *prev_it;
3803 if (prev_par.getDepth() <= cur_depth)
3804 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3806 // start of nested inset: reset
3811 // set the label of a paragraph. This includes the counters.
3812 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3814 BufferParams const & bp = owner_->masterBuffer()->params();
3815 DocumentClass const & textclass = bp.documentClass();
3816 Paragraph & par = it.paragraph();
3817 Layout const & layout = par.layout();
3818 Counters & counters = textclass.counters();
3820 if (par.params().startOfAppendix()) {
3821 // FIXME: only the counter corresponding to toplevel
3822 // sectioning should be reset
3824 counters.appendix(true);
3826 par.params().appendix(counters.appendix());
3828 // Compute the item depth of the paragraph
3829 par.itemdepth = getItemDepth(it);
3831 if (layout.margintype == MARGIN_MANUAL
3832 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3833 if (par.params().labelWidthString().empty())
3834 par.params().labelWidthString(par.expandLabel(layout, bp));
3836 par.params().labelWidthString(docstring());
3839 switch(layout.labeltype) {
3841 if (layout.toclevel <= bp.secnumdepth
3842 && (layout.latextype != LATEX_ENVIRONMENT
3843 || it.text()->isFirstInSequence(it.pit()))) {
3844 counters.step(layout.counter, utype);
3845 par.params().labelString(
3846 par.expandLabel(layout, bp));
3848 par.params().labelString(docstring());
3851 case LABEL_ITEMIZE: {
3852 // At some point of time we should do something more
3853 // clever here, like:
3854 // par.params().labelString(
3855 // bp.user_defined_bullet(par.itemdepth).getText());
3856 // for now, use a simple hardcoded label
3857 docstring itemlabel;
3858 switch (par.itemdepth) {
3860 itemlabel = char_type(0x2022);
3863 itemlabel = char_type(0x2013);
3866 itemlabel = char_type(0x2217);
3869 itemlabel = char_type(0x2219); // or 0x00b7
3872 par.params().labelString(itemlabel);
3876 case LABEL_ENUMERATE: {
3877 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3879 switch (par.itemdepth) {
3888 enumcounter += "iv";
3891 // not a valid enumdepth...
3895 // Maybe we have to reset the enumeration counter.
3896 if (needEnumCounterReset(it))
3897 counters.reset(enumcounter);
3898 counters.step(enumcounter, utype);
3900 string const & lang = par.getParLanguage(bp)->code();
3901 par.params().labelString(counters.theCounter(enumcounter, lang));
3906 case LABEL_SENSITIVE: {
3907 string const & type = counters.current_float();
3908 docstring full_label;
3910 full_label = owner_->B_("Senseless!!! ");
3912 docstring name = owner_->B_(textclass.floats().getType(type).name());
3913 if (counters.hasCounter(from_utf8(type))) {
3914 string const & lang = par.getParLanguage(bp)->code();
3915 counters.step(from_utf8(type), utype);
3916 full_label = bformat(from_ascii("%1$s %2$s:"),
3918 counters.theCounter(from_utf8(type), lang));
3920 full_label = bformat(from_ascii("%1$s #:"), name);
3922 par.params().labelString(full_label);
3926 case LABEL_NO_LABEL:
3927 par.params().labelString(docstring());
3931 case LABEL_TOP_ENVIRONMENT:
3932 case LABEL_CENTERED_TOP_ENVIRONMENT:
3935 par.params().labelString(par.expandLabel(layout, bp));
3941 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3943 LASSERT(parit.pit() == 0, /**/);
3945 // set the position of the text in the buffer to be able
3946 // to resolve macros in it. This has nothing to do with
3947 // labels, but by putting it here we avoid implementing
3948 // a whole bunch of traversal routines just for this call.
3949 parit.text()->setMacrocontextPosition(parit);
3951 depth_type maxdepth = 0;
3952 pit_type const lastpit = parit.lastpit();
3953 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3954 // reduce depth if necessary
3955 parit->params().depth(min(parit->params().depth(), maxdepth));
3956 maxdepth = parit->getMaxDepthAfter();
3958 if (utype == OutputUpdate) {
3959 // track the active counters
3960 // we have to do this for the master buffer, since the local
3961 // buffer isn't tracking anything.
3962 masterBuffer()->params().documentClass().counters().
3963 setActiveLayout(parit->layout());
3966 // set the counter for this paragraph
3967 d->setLabel(parit, utype);
3970 InsetList::const_iterator iit = parit->insetList().begin();
3971 InsetList::const_iterator end = parit->insetList().end();
3972 for (; iit != end; ++iit) {
3973 parit.pos() = iit->pos;
3974 iit->inset->updateBuffer(parit, utype);
3980 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3981 WordLangTuple & word_lang, docstring_list & suggestions) const
3985 suggestions.clear();
3986 word_lang = WordLangTuple();
3987 // OK, we start from here.
3988 DocIterator const end = doc_iterator_end(this);
3989 for (; from != end; from.forwardPos()) {
3990 // We are only interested in text so remove the math CursorSlice.
3991 while (from.inMathed()) {
3995 // If from is at the end of the document (which is possible
3996 // when leaving the mathed) LyX will crash later.
4000 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
4005 // Do not increase progress when from == to, otherwise the word
4006 // count will be wrong.
4016 bool Buffer::reload()
4020 removeAutosaveFile();
4021 // e.g., read-only status could have changed due to version control
4022 d->filename.refresh();
4023 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4025 bool const success = loadLyXFile(d->filename);
4031 message(bformat(_("Document %1$s reloaded."), disp_fn));
4033 message(bformat(_("Could not reload document %1$s."), disp_fn));
4036 thePreviews().removeLoader(*this);
4037 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
4038 thePreviews().generateBufferPreviews(*this);
4044 // FIXME We could do better here, but it is complicated. What would be
4045 // nice is to offer either (a) to save the child buffer to an appropriate
4046 // location, so that it would "move with the master", or else (b) to update
4047 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4048 // complicated, because the code for this lives in GuiView.
4049 void Buffer::checkChildBuffers()
4051 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4052 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4053 for (; it != en; ++it) {
4054 DocIterator dit = it->second;
4055 Buffer * cbuf = const_cast<Buffer *>(it->first);
4056 if (!cbuf || !theBufferList().isLoaded(cbuf))
4058 Inset * inset = dit.nextInset();
4059 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4060 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4061 docstring const & incfile = inset_inc->getParam("filename");
4062 string oldloc = cbuf->absFileName();
4063 string newloc = makeAbsPath(to_utf8(incfile),
4064 onlyPath(absFileName())).absFileName();
4065 if (oldloc == newloc)
4067 // the location of the child file is incorrect.
4068 Alert::warning(_("Included File Invalid"),
4069 bformat(_("Saving this document to a new location has made the file:\n"
4071 "inaccessible. You will need to update the included filename."),
4072 from_utf8(oldloc)));
4074 inset_inc->setChildBuffer(0);
4076 // invalidate cache of children
4077 d->children_positions.clear();
4078 d->position_to_children.clear();