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/MacroTable.h"
76 #include "mathed/MathMacroTemplate.h"
77 #include "mathed/MathSupport.h"
79 #include "frontends/alert.h"
80 #include "frontends/Delegates.h"
81 #include "frontends/WorkAreaManager.h"
83 #include "graphics/Previews.h"
85 #include "support/lassert.h"
86 #include "support/convert.h"
87 #include "support/debug.h"
88 #include "support/docstring_list.h"
89 #include "support/ExceptionMessage.h"
90 #include "support/FileName.h"
91 #include "support/FileNameList.h"
92 #include "support/filetools.h"
93 #include "support/ForkedCalls.h"
94 #include "support/gettext.h"
95 #include "support/gzstream.h"
96 #include "support/lstrings.h"
97 #include "support/lyxalgo.h"
98 #include "support/os.h"
99 #include "support/Package.h"
100 #include "support/Path.h"
101 #include "support/Systemcall.h"
102 #include "support/textutils.h"
103 #include "support/types.h"
105 #include <boost/bind.hpp>
106 #include <boost/shared_ptr.hpp>
118 using namespace lyx::support;
122 namespace Alert = frontend::Alert;
123 namespace os = support::os;
127 // Do not remove the comment below, so we get merge conflict in
128 // independent branches. Instead add your own.
129 int const LYX_FORMAT = 386; // rgh: LyX version for InsetInfo
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
144 class BufferSet : public std::set<Buffer const *> {};
149 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
160 /// search for macro in local (buffer) table or in children
161 MacroData const * getBufferMacro(docstring const & name,
162 DocIterator const & pos) const;
164 /// Update macro table starting with position of it \param it in some
166 void updateMacros(DocIterator & it, DocIterator & scope);
168 void setLabel(ParIterator & it, UpdateType utype) const;
170 void collectRelatives(BufferSet & bufs) const;
172 /** If we have branches that use the file suffix
173 feature, return the file name with suffix appended.
175 support::FileName exportFileName() const;
182 mutable TexRow texrow;
184 /// need to regenerate .tex?
188 mutable bool lyx_clean;
190 /// is autosave needed?
191 mutable bool bak_clean;
193 /// is this a unnamed file (New...)?
199 /// name of the file the buffer is associated with.
202 /** Set to true only when the file is fully loaded.
203 * Used to prevent the premature generation of previews
204 * and by the citation inset.
206 bool file_fully_loaded;
209 mutable TocBackend toc_backend;
212 typedef pair<DocIterator, MacroData> ScopeMacro;
213 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
214 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
215 /// map from the macro name to the position map,
216 /// which maps the macro definition position to the scope and the MacroData.
217 NamePositionScopeMacroMap macros;
218 /// This seem to change the way Buffer::getMacro() works
219 mutable bool macro_lock;
221 /// positions of child buffers in the buffer
222 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
223 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
224 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
225 /// position of children buffers in this buffer
226 BufferPositionMap children_positions;
227 /// map from children inclusion positions to their scope and their buffer
228 PositionScopeBufferMap position_to_children;
230 /// Container for all sort of Buffer dependant errors.
231 map<string, ErrorList> errorLists;
233 /// timestamp and checksum used to test if the file has been externally
234 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
236 unsigned long checksum_;
239 frontend::WorkAreaManager * wa_;
241 frontend::GuiBufferDelegate * gui_;
246 /// A cache for the bibfiles (including bibfiles of loaded child
247 /// documents), needed for appropriate update of natbib labels.
248 mutable support::FileNameList bibfiles_cache_;
250 // FIXME The caching mechanism could be improved. At present, we have a
251 // cache for each Buffer, that caches all the bibliography info for that
252 // Buffer. A more efficient solution would be to have a global cache per
253 // file, and then to construct the Buffer's bibinfo from that.
254 /// A cache for bibliography info
255 mutable BiblioInfo bibinfo_;
256 /// whether the bibinfo cache is valid
257 bool bibinfo_cache_valid_;
258 /// Cache of timestamps of .bib files
259 map<FileName, time_t> bibfile_status_;
261 mutable RefCache ref_cache_;
263 /// our Text that should be wrapped in an InsetText
266 /// This is here to force the test to be done whenever parent_buffer
268 Buffer const * parent() const {
269 // if parent_buffer is not loaded, then it has been unloaded,
270 // which means that parent_buffer is an invalid pointer. So we
271 // set it to null in that case.
272 // however, the BufferList doesn't know about cloned buffers, so
273 // they will always be regarded as unloaded. in that case, we hope
275 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
277 return parent_buffer;
280 void setParent(Buffer const * pb) {
282 && parent_buffer && pb && parent_buffer != pb)
283 LYXERR0("Warning: a buffer should not have two parents!");
287 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
288 /// This one is useful for preview detached in a thread.
289 Buffer const * cloned_buffer_;
292 /// So we can force access via the accessors.
293 mutable Buffer const * parent_buffer;
298 /// Creates the per buffer temporary directory
299 static FileName createBufferTmpDir()
302 // We are in our own directory. Why bother to mangle name?
303 // In fact I wrote this code to circumvent a problematic behaviour
304 // (bug?) of EMX mkstemp().
305 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
306 convert<string>(count++));
308 if (!tmpfl.createDirectory(0777)) {
309 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
310 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
311 from_utf8(tmpfl.absFileName())));
317 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
318 Buffer const * cloned_buffer)
319 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
320 read_only(readonly_), filename(file), file_fully_loaded(false),
321 toc_backend(owner), macro_lock(false), timestamp_(0),
322 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
323 cloned_buffer_(cloned_buffer), parent_buffer(0)
325 if (!cloned_buffer_) {
326 temppath = createBufferTmpDir();
327 lyxvc.setBuffer(owner_);
329 wa_ = new frontend::WorkAreaManager;
332 temppath = cloned_buffer_->d->temppath;
333 file_fully_loaded = true;
334 params = cloned_buffer_->d->params;
335 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
336 bibinfo_ = cloned_buffer_->d->bibinfo_;
337 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
338 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
342 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
343 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
345 LYXERR(Debug::INFO, "Buffer::Buffer()");
347 d->inset = new InsetText(*cloned_buffer->d->inset);
348 d->inset->setBuffer(*this);
349 // FIXME: optimize this loop somewhat, maybe by creating a new
350 // general recursive Inset::setId().
351 DocIterator it = doc_iterator_begin(this);
352 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
353 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
354 it.paragraph().setId(cloned_it.paragraph().id());
356 d->inset = new InsetText(this);
357 d->inset->setAutoBreakRows(true);
358 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
364 LYXERR(Debug::INFO, "Buffer::~Buffer()");
365 // here the buffer should take care that it is
366 // saved properly, before it goes into the void.
368 // GuiView already destroyed
372 // No need to do additional cleanups for internal buffer.
377 // loop over children
378 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
379 Impl::BufferPositionMap::iterator end = d->children_positions.end();
380 for (; it != end; ++it) {
381 Buffer * child = const_cast<Buffer *>(it->first);
382 if (d->cloned_buffer_)
384 // The child buffer might have been closed already.
385 else if (theBufferList().isLoaded(child))
386 theBufferList().releaseChild(this, child);
390 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
391 msg += emergencyWrite();
392 Alert::warning(_("Attempting to close changed document!"), msg);
395 // clear references to children in macro tables
396 d->children_positions.clear();
397 d->position_to_children.clear();
399 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
400 Alert::warning(_("Could not remove temporary directory"),
401 bformat(_("Could not remove the temporary directory %1$s"),
402 from_utf8(d->temppath.absFileName())));
405 // Remove any previewed LaTeX snippets associated with this buffer.
406 thePreviews().removeLoader(*this);
412 Buffer * Buffer::clone() const
414 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
415 buffer_clone->d->macro_lock = true;
416 buffer_clone->d->children_positions.clear();
417 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
418 // math macro caches need to be rethought and simplified.
419 // I am not sure wether we should handle Buffer cloning here or in BufferList.
420 // Right now BufferList knows nothing about buffer clones.
421 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
422 Impl::BufferPositionMap::iterator end = d->children_positions.end();
423 for (; it != end; ++it) {
424 DocIterator dit = it->second.clone(buffer_clone);
425 dit.setBuffer(buffer_clone);
426 Buffer * child = const_cast<Buffer *>(it->first);
427 Buffer * child_clone = child->clone();
428 Inset * inset = dit.nextInset();
429 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
430 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
431 inset_inc->setChildBuffer(child_clone);
432 child_clone->d->setParent(buffer_clone);
433 buffer_clone->setChild(dit, child_clone);
435 buffer_clone->d->macro_lock = false;
440 bool Buffer::isClone() const
442 return d->cloned_buffer_;
446 void Buffer::changed(bool update_metrics) const
449 d->wa_->redrawAll(update_metrics);
453 frontend::WorkAreaManager & Buffer::workAreaManager() const
455 LASSERT(d->wa_, /**/);
460 Text & Buffer::text() const
462 return d->inset->text();
466 Inset & Buffer::inset() const
472 BufferParams & Buffer::params()
478 BufferParams const & Buffer::params() const
484 ParagraphList & Buffer::paragraphs()
486 return text().paragraphs();
490 ParagraphList const & Buffer::paragraphs() const
492 return text().paragraphs();
496 LyXVC & Buffer::lyxvc()
502 LyXVC const & Buffer::lyxvc() const
508 string const Buffer::temppath() const
510 return d->temppath.absFileName();
514 TexRow & Buffer::texrow()
520 TexRow const & Buffer::texrow() const
526 TocBackend & Buffer::tocBackend() const
528 return d->toc_backend;
532 Undo & Buffer::undo()
538 void Buffer::setChild(DocIterator const & dit, Buffer * child)
540 d->children_positions[child] = dit;
544 string Buffer::latexName(bool const no_path) const
546 FileName latex_name =
547 makeLatexName(d->exportFileName());
548 return no_path ? latex_name.onlyFileName()
549 : latex_name.absFileName();
553 FileName Buffer::Impl::exportFileName() const
555 docstring const branch_suffix =
556 params.branchlist().getFilenameSuffix();
557 if (branch_suffix.empty())
560 string const name = filename.onlyFileNameWithoutExt()
561 + to_utf8(branch_suffix);
562 FileName res(filename.onlyPath().absFileName() + "/" + name);
563 res.changeExtension(filename.extension());
569 string Buffer::logName(LogType * type) const
571 string const filename = latexName(false);
573 if (filename.empty()) {
579 string const path = temppath();
581 FileName const fname(addName(temppath(),
582 onlyFileName(changeExtension(filename,
585 // FIXME: how do we know this is the name of the build log?
586 FileName const bname(
587 addName(path, onlyFileName(
588 changeExtension(filename,
589 formats.extension(bufferFormat()) + ".out"))));
591 // Also consider the master buffer log file
592 FileName masterfname = fname;
594 if (masterBuffer() != this) {
595 string const mlogfile = masterBuffer()->logName(&mtype);
596 masterfname = FileName(mlogfile);
599 // If no Latex log or Build log is newer, show Build log
600 if (bname.exists() &&
601 ((!fname.exists() && !masterfname.exists())
602 || (fname.lastModified() < bname.lastModified()
603 && masterfname.lastModified() < bname.lastModified()))) {
604 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
607 return bname.absFileName();
608 // If we have a newer master file log or only a master log, show this
609 } else if (fname != masterfname
610 && (!fname.exists() && (masterfname.exists()
611 || fname.lastModified() < masterfname.lastModified()))) {
612 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
615 return masterfname.absFileName();
617 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
620 return fname.absFileName();
624 void Buffer::setReadonly(bool const flag)
626 if (d->read_only != flag) {
633 void Buffer::setFileName(string const & newfile)
635 d->filename = makeAbsPath(newfile);
636 setReadonly(d->filename.isReadOnly());
641 int Buffer::readHeader(Lexer & lex)
643 int unknown_tokens = 0;
645 int begin_header_line = -1;
647 // Initialize parameters that may be/go lacking in header:
648 params().branchlist().clear();
649 params().preamble.erase();
650 params().options.erase();
651 params().master.erase();
652 params().float_placement.erase();
653 params().paperwidth.erase();
654 params().paperheight.erase();
655 params().leftmargin.erase();
656 params().rightmargin.erase();
657 params().topmargin.erase();
658 params().bottommargin.erase();
659 params().headheight.erase();
660 params().headsep.erase();
661 params().footskip.erase();
662 params().columnsep.erase();
663 params().fontsCJK.erase();
664 params().listings_params.clear();
665 params().clearLayoutModules();
666 params().clearRemovedModules();
667 params().clearIncludedChildren();
668 params().pdfoptions().clear();
669 params().indiceslist().clear();
670 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
671 params().isbackgroundcolor = false;
672 params().fontcolor = lyx::rgbFromHexName("#000000");
673 params().isfontcolor = false;
674 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
675 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
677 for (int i = 0; i < 4; ++i) {
678 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
679 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
682 ErrorList & errorList = d->errorLists["Parse"];
691 if (token == "\\end_header")
695 if (token == "\\begin_header") {
696 begin_header_line = line;
700 LYXERR(Debug::PARSER, "Handling document header token: `"
703 string unknown = params().readToken(lex, token, d->filename.onlyPath());
704 if (!unknown.empty()) {
705 if (unknown[0] != '\\' && token == "\\textclass") {
706 Alert::warning(_("Unknown document class"),
707 bformat(_("Using the default document class, because the "
708 "class %1$s is unknown."), from_utf8(unknown)));
711 docstring const s = bformat(_("Unknown token: "
715 errorList.push_back(ErrorItem(_("Document header error"),
720 if (begin_header_line) {
721 docstring const s = _("\\begin_header is missing");
722 errorList.push_back(ErrorItem(_("Document header error"),
726 params().makeDocumentClass();
728 return unknown_tokens;
733 // changed to be public and have one parameter
734 // Returns true if "\end_document" is not read (Asger)
735 bool Buffer::readDocument(Lexer & lex)
737 ErrorList & errorList = d->errorLists["Parse"];
740 if (!lex.checkFor("\\begin_document")) {
741 docstring const s = _("\\begin_document is missing");
742 errorList.push_back(ErrorItem(_("Document header error"),
746 // we are reading in a brand new document
747 LASSERT(paragraphs().empty(), /**/);
751 if (params().outputChanges) {
752 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
753 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
754 LaTeXFeatures::isAvailable("xcolor");
756 if (!dvipost && !xcolorulem) {
757 Alert::warning(_("Changes not shown in LaTeX output"),
758 _("Changes will not be highlighted in LaTeX output, "
759 "because neither dvipost nor xcolor/ulem are installed.\n"
760 "Please install these packages or redefine "
761 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
762 } else if (!xcolorulem) {
763 Alert::warning(_("Changes not shown in LaTeX output"),
764 _("Changes will not be highlighted in LaTeX output "
765 "when using pdflatex, because xcolor and ulem are not installed.\n"
766 "Please install both packages or redefine "
767 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
771 if (!params().master.empty()) {
772 FileName const master_file = makeAbsPath(params().master,
773 onlyPath(absFileName()));
774 if (isLyXFileName(master_file.absFileName())) {
776 checkAndLoadLyXFile(master_file, true);
778 // necessary e.g. after a reload
779 // to re-register the child (bug 5873)
780 // FIXME: clean up updateMacros (here, only
781 // child registering is needed).
782 master->updateMacros();
783 // set master as master buffer, but only
784 // if we are a real child
785 if (master->isChild(this))
787 // if the master is not fully loaded
788 // it is probably just loading this
789 // child. No warning needed then.
790 else if (master->isFullyLoaded())
791 LYXERR0("The master '"
793 << "' assigned to this document ("
795 << ") does not include "
796 "this document. Ignoring the master assignment.");
801 // assure we have a default index
802 params().indiceslist().addDefault(B_("Index"));
805 bool const res = text().read(lex, errorList, d->inset);
809 updateMacroInstances();
814 bool Buffer::readString(string const & s)
816 params().compressed = false;
818 // remove dummy empty par
819 paragraphs().clear();
823 FileName const name = FileName::tempName("Buffer_readString");
824 switch (readFile(lex, name, true)) {
828 // We need to call lyx2lyx, so write the input to a file
829 ofstream os(name.toFilesystemEncoding().c_str());
832 return readFile(name);
842 bool Buffer::readFile(FileName const & filename)
844 FileName fname(filename);
846 params().compressed = fname.isZippedFile();
848 // remove dummy empty par
849 paragraphs().clear();
852 if (readFile(lex, fname) != success)
859 bool Buffer::isFullyLoaded() const
861 return d->file_fully_loaded;
865 void Buffer::setFullyLoaded(bool value)
867 d->file_fully_loaded = value;
871 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
874 LASSERT(!filename.empty(), /**/);
876 // the first (non-comment) token _must_ be...
877 if (!lex.checkFor("\\lyxformat")) {
878 Alert::error(_("Document format failure"),
879 bformat(_("%1$s is not a readable LyX document."),
880 from_utf8(filename.absFileName())));
886 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
887 // if present remove ".," from string.
888 size_t dot = tmp_format.find_first_of(".,");
889 //lyxerr << " dot found at " << dot << endl;
890 if (dot != string::npos)
891 tmp_format.erase(dot, 1);
892 int const file_format = convert<int>(tmp_format);
893 //lyxerr << "format: " << file_format << endl;
895 // save timestamp and checksum of the original disk file, making sure
896 // to not overwrite them with those of the file created in the tempdir
897 // when it has to be converted to the current format.
899 // Save the timestamp and checksum of disk file. If filename is an
900 // emergency file, save the timestamp and checksum of the original lyx file
901 // because isExternallyModified will check for this file. (BUG4193)
902 string diskfile = filename.absFileName();
903 if (suffixIs(diskfile, ".emergency"))
904 diskfile = diskfile.substr(0, diskfile.size() - 10);
905 saveCheckSum(FileName(diskfile));
908 if (file_format != LYX_FORMAT) {
911 // lyx2lyx would fail
914 FileName const tmpfile = FileName::tempName("Buffer_readFile");
915 if (tmpfile.empty()) {
916 Alert::error(_("Conversion failed"),
917 bformat(_("%1$s is from a different"
918 " version of LyX, but a temporary"
919 " file for converting it could"
921 from_utf8(filename.absFileName())));
924 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
925 if (lyx2lyx.empty()) {
926 Alert::error(_("Conversion script not found"),
927 bformat(_("%1$s is from a different"
928 " version of LyX, but the"
929 " conversion script lyx2lyx"
930 " could not be found."),
931 from_utf8(filename.absFileName())));
934 ostringstream command;
935 command << os::python()
936 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
937 << " -t " << convert<string>(LYX_FORMAT)
938 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
939 << ' ' << quoteName(filename.toSafeFilesystemEncoding());
940 string const command_str = command.str();
942 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
944 cmd_ret const ret = runCommand(command_str);
945 if (ret.first != 0) {
946 if (file_format < LYX_FORMAT)
947 Alert::error(_("Conversion script failed"),
948 bformat(_("%1$s is from an older version"
949 " of LyX, but the lyx2lyx script"
950 " failed to convert it."),
951 from_utf8(filename.absFileName())));
953 Alert::error(_("Conversion script failed"),
954 bformat(_("%1$s is from a newer version"
955 " of LyX and cannot be converted by the"
957 from_utf8(filename.absFileName())));
960 bool const ret = readFile(tmpfile);
961 // Do stuff with tmpfile name and buffer name here.
962 return ret ? success : failure;
967 if (readDocument(lex)) {
968 Alert::error(_("Document format failure"),
969 bformat(_("%1$s ended unexpectedly, which means"
970 " that it is probably corrupted."),
971 from_utf8(filename.absFileName())));
975 d->file_fully_loaded = true;
980 // Should probably be moved to somewhere else: BufferView? GuiView?
981 bool Buffer::save() const
983 // ask if the disk file has been externally modified (use checksum method)
984 if (fileName().exists() && isExternallyModified(checksum_method)) {
985 docstring const file = makeDisplayPath(absFileName(), 20);
986 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
987 "you want to overwrite this file?"), file);
988 int const ret = Alert::prompt(_("Overwrite modified file?"),
989 text, 1, 1, _("&Overwrite"), _("&Cancel"));
994 // We don't need autosaves in the immediate future. (Asger)
995 resetAutosaveTimers();
998 bool madeBackup = false;
1000 // make a backup if the file already exists
1001 if (lyxrc.make_backup && fileName().exists()) {
1002 backupName = FileName(absFileName() + '~');
1003 if (!lyxrc.backupdir_path.empty()) {
1004 string const mangledName =
1005 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1006 backupName = FileName(addName(lyxrc.backupdir_path,
1009 if (fileName().moveTo(backupName)) {
1012 Alert::error(_("Backup failure"),
1013 bformat(_("Cannot create backup file %1$s.\n"
1014 "Please check whether the directory exists and is writeable."),
1015 from_utf8(backupName.absFileName())));
1016 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1020 if (writeFile(d->filename)) {
1024 // Saving failed, so backup is not backup
1026 backupName.moveTo(d->filename);
1032 bool Buffer::writeFile(FileName const & fname) const
1034 if (d->read_only && fname == d->filename)
1037 bool retval = false;
1039 docstring const str = bformat(_("Saving document %1$s..."),
1040 makeDisplayPath(fname.absFileName()));
1043 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1045 if (params().compressed) {
1046 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1047 retval = ofs && write(ofs);
1049 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1050 retval = ofs && write(ofs);
1054 message(str + _(" could not write file!"));
1059 // removeAutosaveFile();
1061 saveCheckSum(d->filename);
1062 message(str + _(" done."));
1068 docstring Buffer::emergencyWrite()
1070 // No need to save if the buffer has not changed.
1074 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1076 docstring user_message = bformat(
1077 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1079 // We try to save three places:
1080 // 1) Same place as document. Unless it is an unnamed doc.
1082 string s = absFileName();
1085 if (writeFile(FileName(s))) {
1087 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1088 return user_message;
1090 user_message += _(" Save failed! Trying again...\n");
1094 // 2) In HOME directory.
1095 string s = addName(package().home_dir().absFileName(), absFileName());
1097 lyxerr << ' ' << s << endl;
1098 if (writeFile(FileName(s))) {
1100 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1101 return user_message;
1104 user_message += _(" Save failed! Trying yet again...\n");
1106 // 3) In "/tmp" directory.
1107 // MakeAbsPath to prepend the current
1108 // drive letter on OS/2
1109 s = addName(package().temp_dir().absFileName(), absFileName());
1111 lyxerr << ' ' << s << endl;
1112 if (writeFile(FileName(s))) {
1114 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1115 return user_message;
1118 user_message += _(" Save failed! Bummer. Document is lost.");
1121 return user_message;
1125 bool Buffer::write(ostream & ofs) const
1128 // Use the standard "C" locale for file output.
1129 ofs.imbue(locale::classic());
1132 // The top of the file should not be written by params().
1134 // write out a comment in the top of the file
1135 ofs << "#LyX " << lyx_version
1136 << " created this file. For more info see http://www.lyx.org/\n"
1137 << "\\lyxformat " << LYX_FORMAT << "\n"
1138 << "\\begin_document\n";
1140 /// For each author, set 'used' to true if there is a change
1141 /// by this author in the document; otherwise set it to 'false'.
1142 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1143 AuthorList::Authors::const_iterator a_end = params().authors().end();
1144 for (; a_it != a_end; ++a_it)
1145 a_it->setUsed(false);
1147 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1148 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1149 for ( ; it != end; ++it)
1150 it->checkAuthors(params().authors());
1152 // now write out the buffer parameters.
1153 ofs << "\\begin_header\n";
1154 params().writeFile(ofs);
1155 ofs << "\\end_header\n";
1158 ofs << "\n\\begin_body\n";
1160 ofs << "\n\\end_body\n";
1162 // Write marker that shows file is complete
1163 ofs << "\\end_document" << endl;
1165 // Shouldn't really be needed....
1168 // how to check if close went ok?
1169 // Following is an attempt... (BE 20001011)
1171 // good() returns false if any error occured, including some
1172 // formatting error.
1173 // bad() returns true if something bad happened in the buffer,
1174 // which should include file system full errors.
1179 lyxerr << "File was not closed properly." << endl;
1186 bool Buffer::makeLaTeXFile(FileName const & fname,
1187 string const & original_path,
1188 OutputParams const & runparams_in,
1189 bool output_preamble, bool output_body) const
1191 OutputParams runparams = runparams_in;
1192 if (params().useXetex)
1193 runparams.flavor = OutputParams::XETEX;
1195 string const encoding = runparams.encoding->iconvName();
1196 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1199 try { ofs.reset(encoding); }
1200 catch (iconv_codecvt_facet_exception & e) {
1201 lyxerr << "Caught iconv exception: " << e.what() << endl;
1202 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1203 "verify that the support software for your encoding (%1$s) is "
1204 "properly installed"), from_ascii(encoding)));
1207 if (!openFileWrite(ofs, fname))
1210 //TexStream ts(ofs.rdbuf(), &texrow());
1211 ErrorList & errorList = d->errorLists["Export"];
1213 bool failed_export = false;
1216 writeLaTeXSource(ofs, original_path,
1217 runparams, output_preamble, output_body);
1219 catch (EncodingException & e) {
1220 odocstringstream ods;
1221 ods.put(e.failed_char);
1223 oss << "0x" << hex << e.failed_char << dec;
1224 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1225 " (code point %2$s)"),
1226 ods.str(), from_utf8(oss.str()));
1227 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1228 "representable in the chosen encoding.\n"
1229 "Changing the document encoding to utf8 could help."),
1230 e.par_id, e.pos, e.pos + 1));
1231 failed_export = true;
1233 catch (iconv_codecvt_facet_exception & e) {
1234 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1235 _(e.what()), -1, 0, 0));
1236 failed_export = true;
1238 catch (exception const & e) {
1239 errorList.push_back(ErrorItem(_("conversion failed"),
1240 _(e.what()), -1, 0, 0));
1241 failed_export = true;
1244 lyxerr << "Caught some really weird exception..." << endl;
1250 failed_export = true;
1251 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1255 return !failed_export;
1259 void Buffer::writeLaTeXSource(odocstream & os,
1260 string const & original_path,
1261 OutputParams const & runparams_in,
1262 bool const output_preamble, bool const output_body) const
1264 // The child documents, if any, shall be already loaded at this point.
1266 OutputParams runparams = runparams_in;
1268 // Classify the unicode characters appearing in math insets
1269 Encodings::initUnicodeMath(*this);
1271 // validate the buffer.
1272 LYXERR(Debug::LATEX, " Validating buffer...");
1273 LaTeXFeatures features(*this, params(), runparams);
1275 LYXERR(Debug::LATEX, " Buffer validation done.");
1277 // The starting paragraph of the coming rows is the
1278 // first paragraph of the document. (Asger)
1279 if (output_preamble && runparams.nice) {
1280 os << "%% LyX " << lyx_version << " created this file. "
1281 "For more info, see http://www.lyx.org/.\n"
1282 "%% Do not edit unless you really know what "
1284 d->texrow.newline();
1285 d->texrow.newline();
1287 LYXERR(Debug::INFO, "lyx document header finished");
1289 // Don't move this behind the parent_buffer=0 code below,
1290 // because then the macros will not get the right "redefinition"
1291 // flag as they don't see the parent macros which are output before.
1294 // fold macros if possible, still with parent buffer as the
1295 // macros will be put in the prefix anyway.
1296 updateMacroInstances();
1298 // There are a few differences between nice LaTeX and usual files:
1299 // usual is \batchmode and has a
1300 // special input@path to allow the including of figures
1301 // with either \input or \includegraphics (what figinsets do).
1302 // input@path is set when the actual parameter
1303 // original_path is set. This is done for usual tex-file, but not
1304 // for nice-latex-file. (Matthias 250696)
1305 // Note that input@path is only needed for something the user does
1306 // in the preamble, included .tex files or ERT, files included by
1307 // LyX work without it.
1308 if (output_preamble) {
1309 if (!runparams.nice) {
1310 // code for usual, NOT nice-latex-file
1311 os << "\\batchmode\n"; // changed
1312 // from \nonstopmode
1313 d->texrow.newline();
1315 if (!original_path.empty()) {
1317 // We don't know the encoding of inputpath
1318 docstring const inputpath = from_utf8(support::latex_path(original_path));
1319 docstring uncodable_glyphs;
1320 Encoding const * const enc = runparams.encoding;
1322 for (size_t n = 0; n < inputpath.size(); ++n) {
1323 docstring const glyph =
1324 docstring(1, inputpath[n]);
1325 if (enc->latexChar(inputpath[n], true) != glyph) {
1326 LYXERR0("Uncodable character '"
1328 << "' in input path!");
1329 uncodable_glyphs += glyph;
1334 // warn user if we found uncodable glyphs.
1335 if (!uncodable_glyphs.empty()) {
1336 frontend::Alert::warning(_("Uncodable character in file path"),
1337 support::bformat(_("The path of your document\n"
1339 "contains glyphs that are unknown in the\n"
1340 "current document encoding (namely %2$s).\n"
1341 "This will likely result in incomplete output.\n\n"
1342 "Choose an appropriate document encoding (such as utf8)\n"
1343 "or change the file path name."), inputpath, uncodable_glyphs));
1345 os << "\\makeatletter\n"
1346 << "\\def\\input@path{{"
1347 << inputpath << "/}}\n"
1348 << "\\makeatother\n";
1349 d->texrow.newline();
1350 d->texrow.newline();
1351 d->texrow.newline();
1355 // get parent macros (if this buffer has a parent) which will be
1356 // written at the document begin further down.
1357 MacroSet parentMacros;
1358 listParentMacros(parentMacros, features);
1360 // Write the preamble
1361 runparams.use_babel = params().writeLaTeX(os, features,
1363 d->filename.onlyPath());
1365 runparams.use_japanese = features.isRequired("japanese");
1371 os << "\\begin{document}\n";
1372 d->texrow.newline();
1374 // output the parent macros
1375 MacroSet::iterator it = parentMacros.begin();
1376 MacroSet::iterator end = parentMacros.end();
1377 for (; it != end; ++it) {
1378 int num_lines = (*it)->write(os, true);
1379 d->texrow.newlines(num_lines);
1382 } // output_preamble
1384 d->texrow.start(paragraphs().begin()->id(), 0);
1386 LYXERR(Debug::INFO, "preamble finished, now the body.");
1388 // if we are doing a real file with body, even if this is the
1389 // child of some other buffer, let's cut the link here.
1390 // This happens for example if only a child document is printed.
1391 Buffer const * save_parent = 0;
1392 if (output_preamble) {
1393 save_parent = d->parent();
1398 latexParagraphs(*this, text(), os, d->texrow, runparams);
1400 // Restore the parenthood if needed
1401 if (output_preamble)
1402 d->setParent(save_parent);
1404 // add this just in case after all the paragraphs
1406 d->texrow.newline();
1408 if (output_preamble) {
1409 os << "\\end{document}\n";
1410 d->texrow.newline();
1411 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1413 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1415 runparams_in.encoding = runparams.encoding;
1417 // Just to be sure. (Asger)
1418 d->texrow.newline();
1420 //for (int i = 0; i<d->texrow.rows(); i++) {
1422 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1423 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1426 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1427 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1431 bool Buffer::isLatex() const
1433 return params().documentClass().outputType() == LATEX;
1437 bool Buffer::isLiterate() const
1439 return params().documentClass().outputType() == LITERATE;
1443 bool Buffer::isDocBook() const
1445 return params().documentClass().outputType() == DOCBOOK;
1449 void Buffer::makeDocBookFile(FileName const & fname,
1450 OutputParams const & runparams,
1451 bool const body_only) const
1453 LYXERR(Debug::LATEX, "makeDocBookFile...");
1456 if (!openFileWrite(ofs, fname))
1459 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1463 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1467 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1468 OutputParams const & runparams,
1469 bool const only_body) const
1471 LaTeXFeatures features(*this, params(), runparams);
1476 DocumentClass const & tclass = params().documentClass();
1477 string const top_element = tclass.latexname();
1480 if (runparams.flavor == OutputParams::XML)
1481 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1484 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1487 if (! tclass.class_header().empty())
1488 os << from_ascii(tclass.class_header());
1489 else if (runparams.flavor == OutputParams::XML)
1490 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1491 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1493 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1495 docstring preamble = from_utf8(params().preamble);
1496 if (runparams.flavor != OutputParams::XML ) {
1497 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1498 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1499 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1500 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1503 string const name = runparams.nice
1504 ? changeExtension(absFileName(), ".sgml") : fname;
1505 preamble += features.getIncludedFiles(name);
1506 preamble += features.getLyXSGMLEntities();
1508 if (!preamble.empty()) {
1509 os << "\n [ " << preamble << " ]";
1514 string top = top_element;
1516 if (runparams.flavor == OutputParams::XML)
1517 top += params().language->code();
1519 top += params().language->code().substr(0, 2);
1522 if (!params().options.empty()) {
1524 top += params().options;
1527 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1528 << " file was created by LyX " << lyx_version
1529 << "\n See http://www.lyx.org/ for more information -->\n";
1531 params().documentClass().counters().reset();
1535 sgml::openTag(os, top);
1537 docbookParagraphs(text(), *this, os, runparams);
1538 sgml::closeTag(os, top_element);
1542 void Buffer::makeLyXHTMLFile(FileName const & fname,
1543 OutputParams const & runparams,
1544 bool const body_only) const
1546 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1549 if (!openFileWrite(ofs, fname))
1552 writeLyXHTMLSource(ofs, runparams, body_only);
1556 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1560 void Buffer::writeLyXHTMLSource(odocstream & os,
1561 OutputParams const & runparams,
1562 bool const only_body) const
1564 LaTeXFeatures features(*this, params(), runparams);
1566 updateBuffer(UpdateMaster, OutputUpdate);
1567 checkBibInfoCache();
1568 d->bibinfo_.makeCitationLabels(*this);
1570 updateMacroInstances();
1573 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1574 << "<!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"
1575 // FIXME Language should be set properly.
1576 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1578 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1579 // FIXME Presumably need to set this right
1580 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1582 docstring const & doctitle = features.htmlTitle();
1584 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1587 os << "\n<!-- Text Class Preamble -->\n"
1588 << features.getTClassHTMLPreamble()
1589 << "\n<!-- Premable Snippets -->\n"
1590 << from_utf8(features.getPreambleSnippets());
1592 os << "\n<!-- Layout-provided Styles -->\n";
1593 docstring const styleinfo = features.getTClassHTMLStyles();
1594 if (!styleinfo.empty()) {
1595 os << "<style type='text/css'>\n"
1599 os << "</head>\n<body>\n";
1603 params().documentClass().counters().reset();
1604 xhtmlParagraphs(text(), *this, xs, runparams);
1606 os << "</body>\n</html>\n";
1610 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1611 // Other flags: -wall -v0 -x
1612 int Buffer::runChktex()
1616 // get LaTeX-Filename
1617 FileName const path(temppath());
1618 string const name = addName(path.absFileName(), latexName());
1619 string const org_path = filePath();
1621 PathChanger p(path); // path to LaTeX file
1622 message(_("Running chktex..."));
1624 // Generate the LaTeX file if neccessary
1625 OutputParams runparams(¶ms().encoding());
1626 runparams.flavor = OutputParams::LATEX;
1627 runparams.nice = false;
1628 runparams.linelen = lyxrc.plaintext_linelen;
1629 makeLaTeXFile(FileName(name), org_path, runparams);
1632 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1633 int const res = chktex.run(terr); // run chktex
1636 Alert::error(_("chktex failure"),
1637 _("Could not run chktex successfully."));
1638 } else if (res > 0) {
1639 ErrorList & errlist = d->errorLists["ChkTeX"];
1641 bufferErrors(terr, errlist);
1652 void Buffer::validate(LaTeXFeatures & features) const
1654 params().validate(features);
1658 for_each(paragraphs().begin(), paragraphs().end(),
1659 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1661 if (lyxerr.debugging(Debug::LATEX)) {
1662 features.showStruct();
1667 void Buffer::getLabelList(vector<docstring> & list) const
1669 // If this is a child document, use the parent's list instead.
1670 Buffer const * const pbuf = d->parent();
1672 pbuf->getLabelList(list);
1677 Toc & toc = d->toc_backend.toc("label");
1678 TocIterator toc_it = toc.begin();
1679 TocIterator end = toc.end();
1680 for (; toc_it != end; ++toc_it) {
1681 if (toc_it->depth() == 0)
1682 list.push_back(toc_it->str());
1687 void Buffer::updateBibfilesCache(UpdateScope scope) const
1689 // If this is a child document, use the parent's cache instead.
1690 Buffer const * const pbuf = d->parent();
1691 if (pbuf && scope != UpdateChildOnly) {
1692 pbuf->updateBibfilesCache();
1696 d->bibfiles_cache_.clear();
1697 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1698 if (it->lyxCode() == BIBTEX_CODE) {
1699 InsetBibtex const & inset =
1700 static_cast<InsetBibtex const &>(*it);
1701 support::FileNameList const bibfiles = inset.getBibFiles();
1702 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1705 } else if (it->lyxCode() == INCLUDE_CODE) {
1706 InsetInclude & inset =
1707 static_cast<InsetInclude &>(*it);
1708 inset.updateBibfilesCache();
1709 support::FileNameList const & bibfiles =
1710 inset.getBibfilesCache();
1711 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1716 // the bibinfo cache is now invalid
1717 d->bibinfo_cache_valid_ = false;
1721 void Buffer::invalidateBibinfoCache()
1723 d->bibinfo_cache_valid_ = false;
1727 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1729 // If this is a child document, use the parent's cache instead.
1730 Buffer const * const pbuf = d->parent();
1731 if (pbuf && scope != UpdateChildOnly)
1732 return pbuf->getBibfilesCache();
1734 // We update the cache when first used instead of at loading time.
1735 if (d->bibfiles_cache_.empty())
1736 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1738 return d->bibfiles_cache_;
1742 BiblioInfo const & Buffer::masterBibInfo() const
1744 // if this is a child document and the parent is already loaded
1745 // use the parent's list instead [ale990412]
1746 Buffer const * const tmp = masterBuffer();
1749 return tmp->masterBibInfo();
1750 return localBibInfo();
1754 BiblioInfo const & Buffer::localBibInfo() const
1760 void Buffer::checkBibInfoCache() const
1762 support::FileNameList const & bibfilesCache = getBibfilesCache();
1763 // compare the cached timestamps with the actual ones.
1764 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1765 support::FileNameList::const_iterator en = bibfilesCache.end();
1766 for (; ei != en; ++ ei) {
1767 time_t lastw = ei->lastModified();
1768 time_t prevw = d->bibfile_status_[*ei];
1769 if (lastw != prevw) {
1770 d->bibinfo_cache_valid_ = false;
1771 d->bibfile_status_[*ei] = lastw;
1775 if (!d->bibinfo_cache_valid_) {
1776 d->bibinfo_.clear();
1777 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1778 it->fillWithBibKeys(d->bibinfo_, it);
1779 d->bibinfo_cache_valid_ = true;
1784 bool Buffer::isDepClean(string const & name) const
1786 DepClean::const_iterator const it = d->dep_clean.find(name);
1787 if (it == d->dep_clean.end())
1793 void Buffer::markDepClean(string const & name)
1795 d->dep_clean[name] = true;
1799 bool Buffer::isExportableFormat(string const & format) const
1801 typedef vector<Format const *> Formats;
1803 formats = exportableFormats(true);
1804 Formats::const_iterator fit = formats.begin();
1805 Formats::const_iterator end = formats.end();
1806 for (; fit != end ; ++fit) {
1807 if ((*fit)->name() == format)
1814 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1817 // FIXME? if there is an Buffer LFUN that can be dispatched even
1818 // if internal, put a switch '(cmd.action)' here.
1824 switch (cmd.action()) {
1826 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1827 flag.setOnOff(isReadonly());
1830 // FIXME: There is need for a command-line import.
1831 //case LFUN_BUFFER_IMPORT:
1833 case LFUN_BUFFER_AUTO_SAVE:
1836 case LFUN_BUFFER_EXPORT_CUSTOM:
1837 // FIXME: Nothing to check here?
1840 case LFUN_BUFFER_EXPORT: {
1841 docstring const arg = cmd.argument();
1842 enable = arg == "custom" || isExportable(to_utf8(arg));
1844 flag.message(bformat(
1845 _("Don't know how to export to format: %1$s"), arg));
1849 case LFUN_BUFFER_CHKTEX:
1850 enable = isLatex() && !lyxrc.chktex_command.empty();
1853 case LFUN_BUILD_PROGRAM:
1854 enable = isExportable("program");
1857 case LFUN_BRANCH_ACTIVATE:
1858 case LFUN_BRANCH_DEACTIVATE: {
1859 BranchList const & branchList = params().branchlist();
1860 docstring const branchName = cmd.argument();
1861 enable = !branchName.empty() && branchList.find(branchName);
1865 case LFUN_BRANCH_ADD:
1866 case LFUN_BRANCHES_RENAME:
1867 case LFUN_BUFFER_PRINT:
1868 // if no Buffer is present, then of course we won't be called!
1871 case LFUN_BUFFER_LANGUAGE:
1872 enable = !isReadonly();
1878 flag.setEnabled(enable);
1883 void Buffer::dispatch(string const & command, DispatchResult & result)
1885 return dispatch(lyxaction.lookupFunc(command), result);
1889 // NOTE We can end up here even if we have no GUI, because we are called
1890 // by LyX::exec to handled command-line requests. So we may need to check
1891 // whether we have a GUI or not. The boolean use_gui holds this information.
1892 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1895 // FIXME? if there is an Buffer LFUN that can be dispatched even
1896 // if internal, put a switch '(cmd.action())' here.
1897 dr.dispatched(false);
1900 string const argument = to_utf8(func.argument());
1901 // We'll set this back to false if need be.
1902 bool dispatched = true;
1903 undo().beginUndoGroup();
1905 switch (func.action()) {
1906 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1907 if (lyxvc().inUse())
1908 lyxvc().toggleReadOnly();
1910 setReadonly(!isReadonly());
1913 case LFUN_BUFFER_EXPORT: {
1914 bool success = doExport(argument, false, false);
1915 dr.setError(!success);
1917 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1922 case LFUN_BUILD_PROGRAM:
1923 doExport("program", true, false);
1926 case LFUN_BUFFER_CHKTEX:
1930 case LFUN_BUFFER_EXPORT_CUSTOM: {
1932 string command = split(argument, format_name, ' ');
1933 Format const * format = formats.getFormat(format_name);
1935 lyxerr << "Format \"" << format_name
1936 << "\" not recognized!"
1941 // The name of the file created by the conversion process
1944 // Output to filename
1945 if (format->name() == "lyx") {
1946 string const latexname = latexName(false);
1947 filename = changeExtension(latexname,
1948 format->extension());
1949 filename = addName(temppath(), filename);
1951 if (!writeFile(FileName(filename)))
1955 doExport(format_name, true, false, filename);
1958 // Substitute $$FName for filename
1959 if (!contains(command, "$$FName"))
1960 command = "( " + command + " ) < $$FName";
1961 command = subst(command, "$$FName", filename);
1963 // Execute the command in the background
1965 call.startscript(Systemcall::DontWait, command);
1969 // FIXME: There is need for a command-line import.
1971 case LFUN_BUFFER_IMPORT:
1976 case LFUN_BUFFER_AUTO_SAVE:
1980 case LFUN_BRANCH_ADD: {
1981 docstring const branch_name = func.argument();
1982 if (branch_name.empty()) {
1986 BranchList & branch_list = params().branchlist();
1987 Branch * branch = branch_list.find(branch_name);
1989 LYXERR0("Branch " << branch_name << " already exists.");
1991 docstring const msg =
1992 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1995 branch_list.add(branch_name);
1996 branch = branch_list.find(branch_name);
1997 string const x11hexname = X11hexname(branch->color());
1998 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1999 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2001 dr.update(Update::Force);
2006 case LFUN_BRANCH_ACTIVATE:
2007 case LFUN_BRANCH_DEACTIVATE: {
2008 BranchList & branchList = params().branchlist();
2009 docstring const branchName = func.argument();
2010 // the case without a branch name is handled elsewhere
2011 if (branchName.empty()) {
2015 Branch * branch = branchList.find(branchName);
2017 LYXERR0("Branch " << branchName << " does not exist.");
2019 docstring const msg =
2020 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2023 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2025 dr.update(Update::Force);
2030 case LFUN_BRANCHES_RENAME: {
2031 if (func.argument().empty())
2034 docstring const oldname = from_utf8(func.getArg(0));
2035 docstring const newname = from_utf8(func.getArg(1));
2036 InsetIterator it = inset_iterator_begin(inset());
2037 InsetIterator const end = inset_iterator_end(inset());
2038 bool success = false;
2039 for (; it != end; ++it) {
2040 if (it->lyxCode() == BRANCH_CODE) {
2041 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2042 if (ins.branch() == oldname) {
2043 undo().recordUndo(it);
2044 ins.rename(newname);
2049 if (it->lyxCode() == INCLUDE_CODE) {
2050 // get buffer of external file
2051 InsetInclude const & ins =
2052 static_cast<InsetInclude const &>(*it);
2053 Buffer * child = ins.getChildBuffer();
2056 child->dispatch(func, dr);
2061 dr.update(Update::Force);
2065 case LFUN_BUFFER_PRINT: {
2066 // we'll assume there's a problem until we succeed
2068 string target = func.getArg(0);
2069 string target_name = func.getArg(1);
2070 string command = func.getArg(2);
2073 || target_name.empty()
2074 || command.empty()) {
2075 LYXERR0("Unable to parse " << func.argument());
2076 docstring const msg =
2077 bformat(_("Unable to parse \"%1$s\""), func.argument());
2081 if (target != "printer" && target != "file") {
2082 LYXERR0("Unrecognized target \"" << target << '"');
2083 docstring const msg =
2084 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2089 bool const update_unincluded =
2090 params().maintain_unincluded_children
2091 && !params().getIncludedChildren().empty();
2092 if (!doExport("dvi", true, update_unincluded)) {
2093 showPrintError(absFileName());
2094 dr.setMessage(_("Error exporting to DVI."));
2098 // Push directory path.
2099 string const path = temppath();
2100 // Prevent the compiler from optimizing away p
2104 // there are three cases here:
2105 // 1. we print to a file
2106 // 2. we print directly to a printer
2107 // 3. we print using a spool command (print to file first)
2110 string const dviname = changeExtension(latexName(true), "dvi");
2112 if (target == "printer") {
2113 if (!lyxrc.print_spool_command.empty()) {
2114 // case 3: print using a spool
2115 string const psname = changeExtension(dviname,".ps");
2116 command += ' ' + lyxrc.print_to_file
2119 + quoteName(dviname);
2121 string command2 = lyxrc.print_spool_command + ' ';
2122 if (target_name != "default") {
2123 command2 += lyxrc.print_spool_printerprefix
2127 command2 += quoteName(psname);
2129 // If successful, then spool command
2130 res = one.startscript(Systemcall::Wait, command);
2133 // If there's no GUI, we have to wait on this command. Otherwise,
2134 // LyX deletes the temporary directory, and with it the spooled
2135 // file, before it can be printed!!
2136 Systemcall::Starttype stype = use_gui ?
2137 Systemcall::DontWait : Systemcall::Wait;
2138 res = one.startscript(stype, command2);
2141 // case 2: print directly to a printer
2142 if (target_name != "default")
2143 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2145 Systemcall::Starttype stype = use_gui ?
2146 Systemcall::DontWait : Systemcall::Wait;
2147 res = one.startscript(stype, command + quoteName(dviname));
2151 // case 1: print to a file
2152 FileName const filename(makeAbsPath(target_name, filePath()));
2153 FileName const dvifile(makeAbsPath(dviname, path));
2154 if (filename.exists()) {
2155 docstring text = bformat(
2156 _("The file %1$s already exists.\n\n"
2157 "Do you want to overwrite that file?"),
2158 makeDisplayPath(filename.absFileName()));
2159 if (Alert::prompt(_("Overwrite file?"),
2160 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2163 command += ' ' + lyxrc.print_to_file
2164 + quoteName(filename.toFilesystemEncoding())
2166 + quoteName(dvifile.toFilesystemEncoding());
2168 Systemcall::Starttype stype = use_gui ?
2169 Systemcall::DontWait : Systemcall::Wait;
2170 res = one.startscript(stype, command);
2176 dr.setMessage(_("Error running external commands."));
2177 showPrintError(absFileName());
2182 case LFUN_BUFFER_LANGUAGE: {
2183 Language const * oldL = params().language;
2184 Language const * newL = languages.getLanguage(argument);
2185 if (!newL || oldL == newL)
2187 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2188 changeLanguage(oldL, newL);
2196 dr.dispatched(dispatched);
2197 undo().endUndoGroup();
2201 void Buffer::changeLanguage(Language const * from, Language const * to)
2203 LASSERT(from, /**/);
2206 for_each(par_iterator_begin(),
2208 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2212 bool Buffer::isMultiLingual() const
2214 ParConstIterator end = par_iterator_end();
2215 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2216 if (it->isMultiLingual(params()))
2223 std::set<Language const *> Buffer::getLanguages() const
2225 std::set<Language const *> languages;
2226 getLanguages(languages);
2231 void Buffer::getLanguages(std::set<Language const *> & languages) const
2233 ParConstIterator end = par_iterator_end();
2234 // add the buffer language, even if it's not actively used
2235 languages.insert(language());
2236 // iterate over the paragraphs
2237 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2238 it->getLanguages(languages);
2240 std::vector<Buffer *> clist = getChildren();
2241 for (vector<Buffer *>::const_iterator cit = clist.begin();
2242 cit != clist.end(); ++cit)
2243 (*cit)->getLanguages(languages);
2247 DocIterator Buffer::getParFromID(int const id) const
2249 Buffer * buf = const_cast<Buffer *>(this);
2251 // John says this is called with id == -1 from undo
2252 lyxerr << "getParFromID(), id: " << id << endl;
2253 return doc_iterator_end(buf);
2256 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2257 if (it.paragraph().id() == id)
2260 return doc_iterator_end(buf);
2264 bool Buffer::hasParWithID(int const id) const
2266 return !getParFromID(id).atEnd();
2270 ParIterator Buffer::par_iterator_begin()
2272 return ParIterator(doc_iterator_begin(this));
2276 ParIterator Buffer::par_iterator_end()
2278 return ParIterator(doc_iterator_end(this));
2282 ParConstIterator Buffer::par_iterator_begin() const
2284 return ParConstIterator(doc_iterator_begin(this));
2288 ParConstIterator Buffer::par_iterator_end() const
2290 return ParConstIterator(doc_iterator_end(this));
2294 Language const * Buffer::language() const
2296 return params().language;
2300 docstring const Buffer::B_(string const & l10n) const
2302 return params().B_(l10n);
2306 bool Buffer::isClean() const
2308 return d->lyx_clean;
2312 bool Buffer::isExternallyModified(CheckMethod method) const
2314 LASSERT(d->filename.exists(), /**/);
2315 // if method == timestamp, check timestamp before checksum
2316 return (method == checksum_method
2317 || d->timestamp_ != d->filename.lastModified())
2318 && d->checksum_ != d->filename.checksum();
2322 void Buffer::saveCheckSum(FileName const & file) const
2324 if (file.exists()) {
2325 d->timestamp_ = file.lastModified();
2326 d->checksum_ = file.checksum();
2328 // in the case of save to a new file.
2335 void Buffer::markClean() const
2337 if (!d->lyx_clean) {
2338 d->lyx_clean = true;
2341 // if the .lyx file has been saved, we don't need an
2343 d->bak_clean = true;
2347 void Buffer::setUnnamed(bool flag)
2353 bool Buffer::isUnnamed() const
2360 /// Don't check unnamed, here: isInternal() is used in
2361 /// newBuffer(), where the unnamed flag has not been set by anyone
2362 /// yet. Also, for an internal buffer, there should be no need for
2363 /// retrieving fileName() nor for checking if it is unnamed or not.
2364 bool Buffer::isInternal() const
2366 return fileName().extension() == "internal";
2370 void Buffer::markDirty()
2373 d->lyx_clean = false;
2376 d->bak_clean = false;
2378 DepClean::iterator it = d->dep_clean.begin();
2379 DepClean::const_iterator const end = d->dep_clean.end();
2381 for (; it != end; ++it)
2386 FileName Buffer::fileName() const
2392 string Buffer::absFileName() const
2394 return d->filename.absFileName();
2398 string Buffer::filePath() const
2400 return d->filename.onlyPath().absFileName() + "/";
2404 bool Buffer::isReadonly() const
2406 return d->read_only;
2410 void Buffer::setParent(Buffer const * buffer)
2412 // Avoids recursive include.
2413 d->setParent(buffer == this ? 0 : buffer);
2418 Buffer const * Buffer::parent() const
2424 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2426 bufs.insert(owner_);
2428 parent()->d->collectRelatives(bufs);
2430 // loop over children
2431 BufferPositionMap::const_iterator it = children_positions.begin();
2432 BufferPositionMap::const_iterator end = children_positions.end();
2433 for (; it != end; ++it)
2434 bufs.insert(const_cast<Buffer *>(it->first));
2438 std::vector<Buffer const *> Buffer::allRelatives() const
2441 d->collectRelatives(bufs);
2442 BufferSet::iterator it = bufs.begin();
2443 std::vector<Buffer const *> ret;
2444 for (; it != bufs.end(); ++it)
2450 Buffer const * Buffer::masterBuffer() const
2452 Buffer const * const pbuf = d->parent();
2456 return pbuf->masterBuffer();
2460 bool Buffer::isChild(Buffer * child) const
2462 return d->children_positions.find(child) != d->children_positions.end();
2466 DocIterator Buffer::firstChildPosition(Buffer const * child)
2468 Impl::BufferPositionMap::iterator it;
2469 it = d->children_positions.find(child);
2470 if (it == d->children_positions.end())
2471 return DocIterator(this);
2476 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2478 // loop over children
2479 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2480 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2481 for (; it != end; ++it) {
2482 Buffer * child = const_cast<Buffer *>(it->first);
2483 clist.push_back(child);
2484 if (grand_children) {
2485 // there might be grandchildren
2486 vector<Buffer *> glist = child->getChildren();
2487 clist.insert(clist.end(), glist.begin(), glist.end());
2493 vector<Buffer *> Buffer::getChildren(bool grand_children) const
2496 getChildren(v, grand_children);
2501 template<typename M>
2502 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2507 typename M::const_iterator it = m.lower_bound(x);
2508 if (it == m.begin())
2516 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2517 DocIterator const & pos) const
2519 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2521 // if paragraphs have no macro context set, pos will be empty
2525 // we haven't found anything yet
2526 DocIterator bestPos = owner_->par_iterator_begin();
2527 MacroData const * bestData = 0;
2529 // find macro definitions for name
2530 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2531 if (nameIt != macros.end()) {
2532 // find last definition in front of pos or at pos itself
2533 PositionScopeMacroMap::const_iterator it
2534 = greatest_below(nameIt->second, pos);
2535 if (it != nameIt->second.end()) {
2537 // scope ends behind pos?
2538 if (pos < it->second.first) {
2539 // Looks good, remember this. If there
2540 // is no external macro behind this,
2541 // we found the right one already.
2542 bestPos = it->first;
2543 bestData = &it->second.second;
2547 // try previous macro if there is one
2548 if (it == nameIt->second.begin())
2555 // find macros in included files
2556 PositionScopeBufferMap::const_iterator it
2557 = greatest_below(position_to_children, pos);
2558 if (it == position_to_children.end())
2559 // no children before
2563 // do we know something better (i.e. later) already?
2564 if (it->first < bestPos )
2567 // scope ends behind pos?
2568 if (pos < it->second.first) {
2569 // look for macro in external file
2571 MacroData const * data
2572 = it->second.second->getMacro(name, false);
2575 bestPos = it->first;
2581 // try previous file if there is one
2582 if (it == position_to_children.begin())
2587 // return the best macro we have found
2592 MacroData const * Buffer::getMacro(docstring const & name,
2593 DocIterator const & pos, bool global) const
2598 // query buffer macros
2599 MacroData const * data = d->getBufferMacro(name, pos);
2603 // If there is a master buffer, query that
2604 Buffer const * const pbuf = d->parent();
2606 d->macro_lock = true;
2607 MacroData const * macro = pbuf->getMacro(
2608 name, *this, false);
2609 d->macro_lock = false;
2615 data = MacroTable::globalMacros().get(name);
2624 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2626 // set scope end behind the last paragraph
2627 DocIterator scope = par_iterator_begin();
2628 scope.pit() = scope.lastpit() + 1;
2630 return getMacro(name, scope, global);
2634 MacroData const * Buffer::getMacro(docstring const & name,
2635 Buffer const & child, bool global) const
2637 // look where the child buffer is included first
2638 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2639 if (it == d->children_positions.end())
2642 // check for macros at the inclusion position
2643 return getMacro(name, it->second, global);
2647 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2649 pit_type const lastpit = it.lastpit();
2651 // look for macros in each paragraph
2652 while (it.pit() <= lastpit) {
2653 Paragraph & par = it.paragraph();
2655 // iterate over the insets of the current paragraph
2656 InsetList const & insets = par.insetList();
2657 InsetList::const_iterator iit = insets.begin();
2658 InsetList::const_iterator end = insets.end();
2659 for (; iit != end; ++iit) {
2660 it.pos() = iit->pos;
2662 // is it a nested text inset?
2663 if (iit->inset->asInsetText()) {
2664 // Inset needs its own scope?
2665 InsetText const * itext = iit->inset->asInsetText();
2666 bool newScope = itext->isMacroScope();
2668 // scope which ends just behind the inset
2669 DocIterator insetScope = it;
2672 // collect macros in inset
2673 it.push_back(CursorSlice(*iit->inset));
2674 updateMacros(it, newScope ? insetScope : scope);
2679 // is it an external file?
2680 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2681 // get buffer of external file
2682 InsetInclude const & inset =
2683 static_cast<InsetInclude const &>(*iit->inset);
2685 Buffer * child = inset.getChildBuffer();
2690 // register its position, but only when it is
2691 // included first in the buffer
2692 if (children_positions.find(child) ==
2693 children_positions.end())
2694 children_positions[child] = it;
2696 // register child with its scope
2697 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2701 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2705 MathMacroTemplate & macroTemplate =
2706 static_cast<MathMacroTemplate &>(*iit->inset);
2707 MacroContext mc(owner_, it);
2708 macroTemplate.updateToContext(mc);
2711 bool valid = macroTemplate.validMacro();
2712 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2713 // then the BufferView's cursor will be invalid in
2714 // some cases which leads to crashes.
2719 // FIXME (Abdel), I don't understandt why we pass 'it' here
2720 // instead of 'macroTemplate' defined above... is this correct?
2721 macros[macroTemplate.name()][it] =
2722 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2732 void Buffer::updateMacros() const
2737 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2739 // start with empty table
2741 d->children_positions.clear();
2742 d->position_to_children.clear();
2744 // Iterate over buffer, starting with first paragraph
2745 // The scope must be bigger than any lookup DocIterator
2746 // later. For the global lookup, lastpit+1 is used, hence
2747 // we use lastpit+2 here.
2748 DocIterator it = par_iterator_begin();
2749 DocIterator outerScope = it;
2750 outerScope.pit() = outerScope.lastpit() + 2;
2751 d->updateMacros(it, outerScope);
2755 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2757 InsetIterator it = inset_iterator_begin(inset());
2758 InsetIterator const end = inset_iterator_end(inset());
2759 for (; it != end; ++it) {
2760 if (it->lyxCode() == BRANCH_CODE) {
2761 InsetBranch & br = static_cast<InsetBranch &>(*it);
2762 docstring const name = br.branch();
2763 if (!from_master && !params().branchlist().find(name))
2764 result.push_back(name);
2765 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2766 result.push_back(name);
2769 if (it->lyxCode() == INCLUDE_CODE) {
2770 // get buffer of external file
2771 InsetInclude const & ins =
2772 static_cast<InsetInclude const &>(*it);
2773 Buffer * child = ins.getChildBuffer();
2776 child->getUsedBranches(result, true);
2779 // remove duplicates
2784 void Buffer::updateMacroInstances() const
2786 LYXERR(Debug::MACROS, "updateMacroInstances for "
2787 << d->filename.onlyFileName());
2788 DocIterator it = doc_iterator_begin(this);
2790 DocIterator const end = doc_iterator_end(this);
2791 for (; it != end; it.forwardInset()) {
2792 // look for MathData cells in InsetMathNest insets
2793 InsetMath * minset = it.nextInset()->asInsetMath();
2797 // update macro in all cells of the InsetMathNest
2798 DocIterator::idx_type n = minset->nargs();
2799 MacroContext mc = MacroContext(this, it);
2800 for (DocIterator::idx_type i = 0; i < n; ++i) {
2801 MathData & data = minset->cell(i);
2802 data.updateMacros(0, mc);
2808 void Buffer::listMacroNames(MacroNameSet & macros) const
2813 d->macro_lock = true;
2815 // loop over macro names
2816 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2817 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2818 for (; nameIt != nameEnd; ++nameIt)
2819 macros.insert(nameIt->first);
2821 // loop over children
2822 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2823 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2824 for (; it != end; ++it)
2825 it->first->listMacroNames(macros);
2828 Buffer const * const pbuf = d->parent();
2830 pbuf->listMacroNames(macros);
2832 d->macro_lock = false;
2836 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2838 Buffer const * const pbuf = d->parent();
2843 pbuf->listMacroNames(names);
2846 MacroNameSet::iterator it = names.begin();
2847 MacroNameSet::iterator end = names.end();
2848 for (; it != end; ++it) {
2850 MacroData const * data =
2851 pbuf->getMacro(*it, *this, false);
2853 macros.insert(data);
2855 // we cannot access the original MathMacroTemplate anymore
2856 // here to calls validate method. So we do its work here manually.
2857 // FIXME: somehow make the template accessible here.
2858 if (data->optionals() > 0)
2859 features.require("xargs");
2865 Buffer::References & Buffer::references(docstring const & label)
2868 return const_cast<Buffer *>(masterBuffer())->references(label);
2870 RefCache::iterator it = d->ref_cache_.find(label);
2871 if (it != d->ref_cache_.end())
2872 return it->second.second;
2874 static InsetLabel const * dummy_il = 0;
2875 static References const dummy_refs;
2876 it = d->ref_cache_.insert(
2877 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2878 return it->second.second;
2882 Buffer::References const & Buffer::references(docstring const & label) const
2884 return const_cast<Buffer *>(this)->references(label);
2888 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2890 masterBuffer()->d->ref_cache_[label].first = il;
2894 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2896 return masterBuffer()->d->ref_cache_[label].first;
2900 void Buffer::clearReferenceCache() const
2903 d->ref_cache_.clear();
2907 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2910 //FIXME: This does not work for child documents yet.
2911 LASSERT(code == CITE_CODE, /**/);
2912 // Check if the label 'from' appears more than once
2913 vector<docstring> labels;
2915 checkBibInfoCache();
2916 BiblioInfo const & keys = masterBibInfo();
2917 BiblioInfo::const_iterator bit = keys.begin();
2918 BiblioInfo::const_iterator bend = keys.end();
2920 for (; bit != bend; ++bit)
2922 labels.push_back(bit->first);
2925 if (count(labels.begin(), labels.end(), from) > 1)
2928 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2929 if (it->lyxCode() == code) {
2930 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2931 docstring const oldValue = inset.getParam(paramName);
2932 if (oldValue == from)
2933 inset.setParam(paramName, to);
2939 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2940 pit_type par_end, bool full_source) const
2942 OutputParams runparams(¶ms().encoding());
2943 runparams.nice = true;
2944 runparams.flavor = params().useXetex ?
2945 OutputParams::XETEX : OutputParams::LATEX;
2946 runparams.linelen = lyxrc.plaintext_linelen;
2947 // No side effect of file copying and image conversion
2948 runparams.dryrun = true;
2951 os << "% " << _("Preview source code") << "\n\n";
2953 d->texrow.newline();
2954 d->texrow.newline();
2956 writeDocBookSource(os, absFileName(), runparams, false);
2958 // latex or literate
2959 writeLaTeXSource(os, string(), runparams, true, true);
2961 runparams.par_begin = par_begin;
2962 runparams.par_end = par_end;
2963 if (par_begin + 1 == par_end) {
2965 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2969 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2970 convert<docstring>(par_begin),
2971 convert<docstring>(par_end - 1))
2978 // output paragraphs
2980 docbookParagraphs(text(), *this, os, runparams);
2982 // latex or literate
2983 latexParagraphs(*this, text(), os, texrow, runparams);
2988 ErrorList & Buffer::errorList(string const & type) const
2990 static ErrorList emptyErrorList;
2991 map<string, ErrorList>::iterator it = d->errorLists.find(type);
2992 if (it == d->errorLists.end())
2993 return emptyErrorList;
2999 void Buffer::updateTocItem(std::string const & type,
3000 DocIterator const & dit) const
3003 d->gui_->updateTocItem(type, dit);
3007 void Buffer::structureChanged() const
3010 d->gui_->structureChanged();
3014 void Buffer::errors(string const & err, bool from_master) const
3017 d->gui_->errors(err, from_master);
3021 void Buffer::message(docstring const & msg) const
3024 d->gui_->message(msg);
3028 void Buffer::setBusy(bool on) const
3031 d->gui_->setBusy(on);
3035 void Buffer::updateTitles() const
3038 d->wa_->updateTitles();
3042 void Buffer::resetAutosaveTimers() const
3045 d->gui_->resetAutosaveTimers();
3049 bool Buffer::hasGuiDelegate() const
3055 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3064 class AutoSaveBuffer : public ForkedProcess {
3067 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3068 : buffer_(buffer), fname_(fname) {}
3070 virtual boost::shared_ptr<ForkedProcess> clone() const
3072 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3077 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3078 from_utf8(fname_.absFileName())));
3079 return run(DontWait);
3083 virtual int generateChild();
3085 Buffer const & buffer_;
3090 int AutoSaveBuffer::generateChild()
3092 #if defined(__APPLE__)
3093 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3094 * We should use something else like threads.
3096 * Since I do not know how to determine at run time what is the OS X
3097 * version, I just disable forking altogether for now (JMarc)
3099 pid_t const pid = -1;
3101 // tmp_ret will be located (usually) in /tmp
3102 // will that be a problem?
3103 // Note that this calls ForkedCalls::fork(), so it's
3104 // ok cross-platform.
3105 pid_t const pid = fork();
3106 // If you want to debug the autosave
3107 // you should set pid to -1, and comment out the fork.
3108 if (pid != 0 && pid != -1)
3112 // pid = -1 signifies that lyx was unable
3113 // to fork. But we will do the save
3115 bool failed = false;
3116 FileName const tmp_ret = FileName::tempName("lyxauto");
3117 if (!tmp_ret.empty()) {
3118 buffer_.writeFile(tmp_ret);
3119 // assume successful write of tmp_ret
3120 if (!tmp_ret.moveTo(fname_))
3126 // failed to write/rename tmp_ret so try writing direct
3127 if (!buffer_.writeFile(fname_)) {
3128 // It is dangerous to do this in the child,
3129 // but safe in the parent, so...
3130 if (pid == -1) // emit message signal.
3131 buffer_.message(_("Autosave failed!"));
3135 if (pid == 0) // we are the child so...
3144 FileName Buffer::getAutosaveFileName() const
3146 // if the document is unnamed try to save in the backup dir, else
3147 // in the default document path, and as a last try in the filePath,
3148 // which will most often be the temporary directory
3151 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3152 : lyxrc.backupdir_path;
3153 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3156 string const fname = "#" + d->filename.onlyFileName() + "#";
3157 return makeAbsPath(fname, fpath);
3161 void Buffer::removeAutosaveFile() const
3163 FileName const f = getAutosaveFileName();
3169 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3171 FileName const newauto = getAutosaveFileName();
3173 if (newauto != oldauto && oldauto.exists())
3174 if (!oldauto.moveTo(newauto))
3175 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3179 // Perfect target for a thread...
3180 void Buffer::autoSave() const
3182 if (d->bak_clean || isReadonly()) {
3183 // We don't save now, but we'll try again later
3184 resetAutosaveTimers();
3188 // emit message signal.
3189 message(_("Autosaving current document..."));
3190 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3193 d->bak_clean = true;
3195 resetAutosaveTimers();
3199 string Buffer::bufferFormat() const
3201 string format = params().documentClass().outputFormat();
3202 if (format == "latex") {
3203 if (params().useXetex)
3205 if (params().encoding().package() == Encoding::japanese)
3212 string Buffer::getDefaultOutputFormat() const
3214 if (!params().defaultOutputFormat.empty()
3215 && params().defaultOutputFormat != "default")
3216 return params().defaultOutputFormat;
3217 typedef vector<Format const *> Formats;
3218 Formats formats = exportableFormats(true);
3221 || params().useXetex
3222 || params().encoding().package() == Encoding::japanese) {
3223 if (formats.empty())
3225 // return the first we find
3226 return formats.front()->name();
3228 return lyxrc.default_view_format;
3233 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3234 bool includeall, string & result_file) const
3236 string backend_format;
3237 OutputParams runparams(¶ms().encoding());
3238 runparams.flavor = OutputParams::LATEX;
3239 runparams.linelen = lyxrc.plaintext_linelen;
3240 runparams.includeall = includeall;
3241 vector<string> backs = backends();
3242 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3243 // Get shortest path to format
3244 Graph::EdgePath path;
3245 for (vector<string>::const_iterator it = backs.begin();
3246 it != backs.end(); ++it) {
3247 Graph::EdgePath p = theConverters().getPath(*it, format);
3248 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3249 backend_format = *it;
3254 if (!put_in_tempdir) {
3255 // Only show this alert if this is an export to a non-temporary
3256 // file (not for previewing).
3257 Alert::error(_("Couldn't export file"), bformat(
3258 _("No information for exporting the format %1$s."),
3259 formats.prettyName(format)));
3263 runparams.flavor = theConverters().getFlavor(path);
3266 backend_format = format;
3267 // FIXME: Don't hardcode format names here, but use a flag
3268 if (backend_format == "pdflatex")
3269 runparams.flavor = OutputParams::PDFLATEX;
3272 string filename = latexName(false);
3273 filename = addName(temppath(), filename);
3274 filename = changeExtension(filename,
3275 formats.extension(backend_format));
3278 updateMacroInstances();
3280 // Plain text backend
3281 if (backend_format == "text") {
3282 runparams.flavor = OutputParams::TEXT;
3283 writePlaintextFile(*this, FileName(filename), runparams);
3286 else if (backend_format == "xhtml") {
3287 runparams.flavor = OutputParams::HTML;
3288 switch (params().html_math_output) {
3289 case BufferParams::MathML:
3290 runparams.math_flavor = OutputParams::MathAsMathML;
3292 case BufferParams::HTML:
3293 runparams.math_flavor = OutputParams::MathAsHTML;
3295 case BufferParams::Images:
3296 runparams.math_flavor = OutputParams::MathAsImages;
3298 case BufferParams::LaTeX:
3299 runparams.math_flavor = OutputParams::MathAsLaTeX;
3303 makeLyXHTMLFile(FileName(filename), runparams);
3304 } else if (backend_format == "lyx")
3305 writeFile(FileName(filename));
3307 else if (isDocBook()) {
3308 runparams.nice = !put_in_tempdir;
3309 makeDocBookFile(FileName(filename), runparams);
3312 else if (backend_format == format) {
3313 runparams.nice = true;
3314 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3316 } else if (!lyxrc.tex_allows_spaces
3317 && contains(filePath(), ' ')) {
3318 Alert::error(_("File name error"),
3319 _("The directory path to the document cannot contain spaces."));
3322 runparams.nice = false;
3323 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3327 string const error_type = (format == "program")
3328 ? "Build" : bufferFormat();
3329 ErrorList & error_list = d->errorLists[error_type];
3330 string const ext = formats.extension(format);
3331 FileName const tmp_result_file(changeExtension(filename, ext));
3332 bool const success = theConverters().convert(this, FileName(filename),
3333 tmp_result_file, FileName(absFileName()), backend_format, format,
3336 // Emit the signal to show the error list or copy it back to the
3337 // cloned Buffer so that it cab be emitted afterwards.
3338 if (format != backend_format) {
3339 if (d->cloned_buffer_) {
3340 d->cloned_buffer_->d->errorLists[error_type] =
3341 d->errorLists[error_type];
3344 // also to the children, in case of master-buffer-view
3345 std::vector<Buffer *> clist = getChildren();
3346 for (vector<Buffer *>::const_iterator cit = clist.begin();
3347 cit != clist.end(); ++cit) {
3348 if (d->cloned_buffer_) {
3349 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3350 (*cit)->d->errorLists[error_type];
3352 (*cit)->errors(error_type, true);
3356 if (d->cloned_buffer_) {
3357 // Enable reverse dvi or pdf to work by copying back the texrow
3358 // object to the cloned buffer.
3359 // FIXME: There is a possibility of concurrent access to texrow
3360 // here from the main GUI thread that should be securized.
3361 d->cloned_buffer_->d->texrow = d->texrow;
3362 string const error_type = bufferFormat();
3363 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3369 if (put_in_tempdir) {
3370 result_file = tmp_result_file.absFileName();
3374 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3375 // We need to copy referenced files (e. g. included graphics
3376 // if format == "dvi") to the result dir.
3377 vector<ExportedFile> const files =
3378 runparams.exportdata->externalFiles(format);
3379 string const dest = onlyPath(result_file);
3380 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3381 : force_overwrite == ALL_FILES;
3382 CopyStatus status = use_force ? FORCE : SUCCESS;
3384 vector<ExportedFile>::const_iterator it = files.begin();
3385 vector<ExportedFile>::const_iterator const en = files.end();
3386 for (; it != en && status != CANCEL; ++it) {
3387 string const fmt = formats.getFormatFromFile(it->sourceName);
3388 status = copyFile(fmt, it->sourceName,
3389 makeAbsPath(it->exportName, dest),
3390 it->exportName, status == FORCE);
3393 if (status == CANCEL) {
3394 message(_("Document export cancelled."));
3395 } else if (tmp_result_file.exists()) {
3396 // Finally copy the main file
3397 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3398 : force_overwrite != NO_FILES;
3399 if (status == SUCCESS && use_force)
3401 status = copyFile(format, tmp_result_file,
3402 FileName(result_file), result_file,
3404 message(bformat(_("Document exported as %1$s "
3406 formats.prettyName(format),
3407 makeDisplayPath(result_file)));
3409 // This must be a dummy converter like fax (bug 1888)
3410 message(bformat(_("Document exported as %1$s"),
3411 formats.prettyName(format)));
3418 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3419 bool includeall) const
3422 // (1) export with all included children (omit \includeonly)
3423 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3425 // (2) export with included children only
3426 return doExport(format, put_in_tempdir, false, result_file);
3430 bool Buffer::preview(string const & format, bool includeall) const
3433 // (1) export with all included children (omit \includeonly)
3434 if (includeall && !doExport(format, true, true))
3436 // (2) export with included children only
3437 if (!doExport(format, true, false, result_file))
3439 return formats.view(*this, FileName(result_file), format);
3443 bool Buffer::isExportable(string const & format) const
3445 vector<string> backs = backends();
3446 for (vector<string>::const_iterator it = backs.begin();
3447 it != backs.end(); ++it)
3448 if (theConverters().isReachable(*it, format))
3454 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3456 vector<string> const backs = backends();
3457 vector<Format const *> result =
3458 theConverters().getReachable(backs[0], only_viewable, true);
3459 for (vector<string>::const_iterator it = backs.begin() + 1;
3460 it != backs.end(); ++it) {
3461 vector<Format const *> r =
3462 theConverters().getReachable(*it, only_viewable, false);
3463 result.insert(result.end(), r.begin(), r.end());
3469 vector<string> Buffer::backends() const
3472 v.push_back(bufferFormat());
3473 // FIXME: Don't hardcode format names here, but use a flag
3474 if (v.back() == "latex")
3475 v.push_back("pdflatex");
3476 v.push_back("xhtml");
3477 v.push_back("text");
3483 bool Buffer::readFileHelper(FileName const & s)
3485 // File information about normal file
3487 docstring const file = makeDisplayPath(s.absFileName(), 50);
3488 docstring text = bformat(_("The specified document\n%1$s"
3489 "\ncould not be read."), file);
3490 Alert::error(_("Could not read document"), text);
3494 // Check if emergency save file exists and is newer.
3495 FileName const e(s.absFileName() + ".emergency");
3497 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3498 docstring const file = makeDisplayPath(s.absFileName(), 20);
3499 docstring const text =
3500 bformat(_("An emergency save of the document "
3502 "Recover emergency save?"), file);
3503 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3504 _("&Recover"), _("&Load Original"),
3508 // the file is not saved if we load the emergency file.
3513 if ((res = readFile(e)) == success)
3514 str = _("Document was successfully recovered.");
3516 str = _("Document was NOT successfully recovered.");
3517 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3518 makeDisplayPath(e.absFileName()));
3520 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3521 _("&Remove"), _("&Keep it"))) {
3524 Alert::warning(_("Emergency file deleted"),
3525 _("Do not forget to save your file now!"), true);
3530 if (!Alert::prompt(_("Delete emergency file?"),
3531 _("Remove emergency file now?"), 1, 1,
3532 _("&Remove"), _("&Keep it")))
3540 // Now check if autosave file is newer.
3541 FileName const a(onlyPath(s.absFileName()) + '#' + onlyFileName(s.absFileName()) + '#');
3543 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3544 docstring const file = makeDisplayPath(s.absFileName(), 20);
3545 docstring const text =
3546 bformat(_("The backup of the document "
3547 "%1$s is newer.\n\nLoad the "
3548 "backup instead?"), file);
3549 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3550 _("&Load backup"), _("Load &original"),
3554 // the file is not saved if we load the autosave file.
3558 // Here we delete the autosave
3569 bool Buffer::loadLyXFile(FileName const & s)
3571 // If the file is not readable, we try to
3572 // retrieve the file from version control.
3573 if (!s.isReadableFile()
3574 && !LyXVC::file_not_found_hook(s))
3577 if (s.isReadableFile()){
3578 // InsetInfo needs to know if file is under VCS
3579 lyxvc().file_found_hook(s);
3580 if (readFileHelper(s)) {
3581 d->read_only = !s.isWritable();
3589 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3591 TeXErrors::Errors::const_iterator cit = terr.begin();
3592 TeXErrors::Errors::const_iterator end = terr.end();
3594 for (; cit != end; ++cit) {
3597 int errorRow = cit->error_in_line;
3598 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3604 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3605 } while (found && id_start == id_end && pos_start == pos_end);
3607 errorList.push_back(ErrorItem(cit->error_desc,
3608 cit->error_text, id_start, pos_start, pos_end));
3613 void Buffer::setBuffersForInsets() const
3615 inset().setBuffer(const_cast<Buffer &>(*this));
3619 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3621 // Use the master text class also for child documents
3622 Buffer const * const master = masterBuffer();
3623 DocumentClass const & textclass = master->params().documentClass();
3625 // do this only if we are the top-level Buffer
3626 if (scope != UpdateMaster || master == this)
3627 checkBibInfoCache();
3629 // keep the buffers to be children in this set. If the call from the
3630 // master comes back we can see which of them were actually seen (i.e.
3631 // via an InsetInclude). The remaining ones in the set need still be updated.
3632 static std::set<Buffer const *> bufToUpdate;
3633 if (scope == UpdateMaster) {
3634 // If this is a child document start with the master
3635 if (master != this) {
3636 bufToUpdate.insert(this);
3637 master->updateBuffer(UpdateMaster, utype);
3638 // Do this here in case the master has no gui associated with it. Then,
3639 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3640 if (!master->d->gui_)
3643 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3644 if (bufToUpdate.find(this) == bufToUpdate.end())
3648 // start over the counters in the master
3649 textclass.counters().reset();
3652 // update will be done below for this buffer
3653 bufToUpdate.erase(this);
3655 // update all caches
3656 clearReferenceCache();
3659 Buffer & cbuf = const_cast<Buffer &>(*this);
3661 LASSERT(!text().paragraphs().empty(), /**/);
3664 ParIterator parit = cbuf.par_iterator_begin();
3665 updateBuffer(parit, utype);
3668 // TocBackend update will be done later.
3671 cbuf.tocBackend().update();
3672 if (scope == UpdateMaster)
3673 cbuf.structureChanged();
3677 static depth_type getDepth(DocIterator const & it)
3679 depth_type depth = 0;
3680 for (size_t i = 0 ; i < it.depth() ; ++i)
3681 if (!it[i].inset().inMathed())
3682 depth += it[i].paragraph().getDepth() + 1;
3683 // remove 1 since the outer inset does not count
3687 static depth_type getItemDepth(ParIterator const & it)
3689 Paragraph const & par = *it;
3690 LabelType const labeltype = par.layout().labeltype;
3692 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3695 // this will hold the lowest depth encountered up to now.
3696 depth_type min_depth = getDepth(it);
3697 ParIterator prev_it = it;
3700 --prev_it.top().pit();
3702 // start of nested inset: go to outer par
3704 if (prev_it.empty()) {
3705 // start of document: nothing to do
3710 // We search for the first paragraph with same label
3711 // that is not more deeply nested.
3712 Paragraph & prev_par = *prev_it;
3713 depth_type const prev_depth = getDepth(prev_it);
3714 if (labeltype == prev_par.layout().labeltype) {
3715 if (prev_depth < min_depth)
3716 return prev_par.itemdepth + 1;
3717 if (prev_depth == min_depth)
3718 return prev_par.itemdepth;
3720 min_depth = min(min_depth, prev_depth);
3721 // small optimization: if we are at depth 0, we won't
3722 // find anything else
3723 if (prev_depth == 0)
3729 static bool needEnumCounterReset(ParIterator const & it)
3731 Paragraph const & par = *it;
3732 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3733 depth_type const cur_depth = par.getDepth();
3734 ParIterator prev_it = it;
3735 while (prev_it.pit()) {
3736 --prev_it.top().pit();
3737 Paragraph const & prev_par = *prev_it;
3738 if (prev_par.getDepth() <= cur_depth)
3739 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3741 // start of nested inset: reset
3746 // set the label of a paragraph. This includes the counters.
3747 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3749 BufferParams const & bp = owner_->masterBuffer()->params();
3750 DocumentClass const & textclass = bp.documentClass();
3751 Paragraph & par = it.paragraph();
3752 Layout const & layout = par.layout();
3753 Counters & counters = textclass.counters();
3755 if (par.params().startOfAppendix()) {
3756 // FIXME: only the counter corresponding to toplevel
3757 // sectioning should be reset
3759 counters.appendix(true);
3761 par.params().appendix(counters.appendix());
3763 // Compute the item depth of the paragraph
3764 par.itemdepth = getItemDepth(it);
3766 if (layout.margintype == MARGIN_MANUAL
3767 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3768 if (par.params().labelWidthString().empty())
3769 par.params().labelWidthString(par.expandLabel(layout, bp));
3771 par.params().labelWidthString(docstring());
3774 switch(layout.labeltype) {
3776 if (layout.toclevel <= bp.secnumdepth
3777 && (layout.latextype != LATEX_ENVIRONMENT
3778 || it.text()->isFirstInSequence(it.pit()))) {
3779 counters.step(layout.counter, utype);
3780 par.params().labelString(
3781 par.expandLabel(layout, bp));
3783 par.params().labelString(docstring());
3786 case LABEL_ITEMIZE: {
3787 // At some point of time we should do something more
3788 // clever here, like:
3789 // par.params().labelString(
3790 // bp.user_defined_bullet(par.itemdepth).getText());
3791 // for now, use a simple hardcoded label
3792 docstring itemlabel;
3793 switch (par.itemdepth) {
3795 itemlabel = char_type(0x2022);
3798 itemlabel = char_type(0x2013);
3801 itemlabel = char_type(0x2217);
3804 itemlabel = char_type(0x2219); // or 0x00b7
3807 par.params().labelString(itemlabel);
3811 case LABEL_ENUMERATE: {
3812 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3814 switch (par.itemdepth) {
3823 enumcounter += "iv";
3826 // not a valid enumdepth...
3830 // Maybe we have to reset the enumeration counter.
3831 if (needEnumCounterReset(it))
3832 counters.reset(enumcounter);
3833 counters.step(enumcounter, utype);
3835 string const & lang = par.getParLanguage(bp)->code();
3836 par.params().labelString(counters.theCounter(enumcounter, lang));
3841 case LABEL_SENSITIVE: {
3842 string const & type = counters.current_float();
3843 docstring full_label;
3845 full_label = owner_->B_("Senseless!!! ");
3847 docstring name = owner_->B_(textclass.floats().getType(type).name());
3848 if (counters.hasCounter(from_utf8(type))) {
3849 string const & lang = par.getParLanguage(bp)->code();
3850 counters.step(from_utf8(type), utype);
3851 full_label = bformat(from_ascii("%1$s %2$s:"),
3853 counters.theCounter(from_utf8(type), lang));
3855 full_label = bformat(from_ascii("%1$s #:"), name);
3857 par.params().labelString(full_label);
3861 case LABEL_NO_LABEL:
3862 par.params().labelString(docstring());
3866 case LABEL_TOP_ENVIRONMENT:
3867 case LABEL_CENTERED_TOP_ENVIRONMENT:
3870 par.params().labelString(par.expandLabel(layout, bp));
3876 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3878 LASSERT(parit.pit() == 0, /**/);
3880 // set the position of the text in the buffer to be able
3881 // to resolve macros in it. This has nothing to do with
3882 // labels, but by putting it here we avoid implementing
3883 // a whole bunch of traversal routines just for this call.
3884 parit.text()->setMacrocontextPosition(parit);
3886 depth_type maxdepth = 0;
3887 pit_type const lastpit = parit.lastpit();
3888 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3889 // reduce depth if necessary
3890 parit->params().depth(min(parit->params().depth(), maxdepth));
3891 maxdepth = parit->getMaxDepthAfter();
3893 if (utype == OutputUpdate) {
3894 // track the active counters
3895 // we have to do this for the master buffer, since the local
3896 // buffer isn't tracking anything.
3897 masterBuffer()->params().documentClass().counters().
3898 setActiveLayout(parit->layout());
3901 // set the counter for this paragraph
3902 d->setLabel(parit, utype);
3905 InsetList::const_iterator iit = parit->insetList().begin();
3906 InsetList::const_iterator end = parit->insetList().end();
3907 for (; iit != end; ++iit) {
3908 parit.pos() = iit->pos;
3909 iit->inset->updateBuffer(parit, utype);
3915 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3916 WordLangTuple & word_lang, docstring_list & suggestions) const
3920 suggestions.clear();
3921 word_lang = WordLangTuple();
3922 // OK, we start from here.
3923 DocIterator const end = doc_iterator_end(this);
3924 for (; from != end; from.forwardPos()) {
3925 // We are only interested in text so remove the math CursorSlice.
3926 while (from.inMathed()) {
3930 // If from is at the end of the document (which is possible
3931 // when leaving the mathed) LyX will crash later.
3935 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3940 // Do not increase progress when from == to, otherwise the word
3941 // count will be wrong.
3951 bool Buffer::reload()
3955 removeAutosaveFile();
3956 // e.g., read-only status could have changed due to version control
3957 d->filename.refresh();
3958 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
3960 bool const success = loadLyXFile(d->filename);
3965 message(bformat(_("Document %1$s reloaded."), disp_fn));
3967 message(bformat(_("Could not reload document %1$s."), disp_fn));
3970 thePreviews().removeLoader(*this);
3971 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
3972 thePreviews().generateBufferPreviews(*this);
3978 // FIXME We could do better here, but it is complicated. What would be
3979 // nice is to offer either (a) to save the child buffer to an appropriate
3980 // location, so that it would "move with the master", or else (b) to update
3981 // the InsetInclude so that it pointed to the same file. But (a) is a bit
3982 // complicated, because the code for this lives in GuiView.
3983 void Buffer::checkChildBuffers()
3985 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3986 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
3987 for (; it != en; ++it) {
3988 DocIterator dit = it->second;
3989 Buffer * cbuf = const_cast<Buffer *>(it->first);
3990 if (!cbuf || !theBufferList().isLoaded(cbuf))
3992 Inset * inset = dit.nextInset();
3993 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
3994 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
3995 docstring const & incfile = inset_inc->getParam("filename");
3996 string oldloc = cbuf->absFileName();
3997 string newloc = makeAbsPath(to_utf8(incfile),
3998 onlyPath(absFileName())).absFileName();
3999 if (oldloc == newloc)
4001 // the location of the child file is incorrect.
4002 Alert::warning(_("Included File Invalid"),
4003 bformat(_("Saving this document to a new location has made the file:\n"
4005 "inaccessible. You will need to update the included filename."),
4006 from_utf8(oldloc)));
4008 inset_inc->setChildBuffer(0);
4010 // invalidate cache of children
4011 d->children_positions.clear();
4012 d->position_to_children.clear();