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_funcs.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 369; // vfr: add author ids to list of authors
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer & parent, FileName const & file, bool readonly);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfilesCache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfoCacheValid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfileStatus_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 if (!theBufferList().isLoaded(parent_buffer))
253 return parent_buffer;
256 void setParent(Buffer const * pb) { parent_buffer = pb; }
258 /// So we can force access via the accessors.
259 mutable Buffer const * parent_buffer;
263 /// Creates the per buffer temporary directory
264 static FileName createBufferTmpDir()
267 // We are in our own directory. Why bother to mangle name?
268 // In fact I wrote this code to circumvent a problematic behaviour
269 // (bug?) of EMX mkstemp().
270 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
271 convert<string>(count++));
273 if (!tmpfl.createDirectory(0777)) {
274 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
275 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
276 from_utf8(tmpfl.absFilename())));
282 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
283 : lyx_clean(true), bak_clean(true), unnamed(false),
284 read_only(readonly_), filename(file), file_fully_loaded(false),
285 toc_backend(&parent), macro_lock(false), timestamp_(0),
286 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
289 temppath = createBufferTmpDir();
290 lyxvc.setBuffer(&parent);
292 wa_ = new frontend::WorkAreaManager;
296 Buffer::Buffer(string const & file, bool readonly)
297 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
299 LYXERR(Debug::INFO, "Buffer::Buffer()");
301 d->inset = new InsetText(*this);
302 d->inset->setAutoBreakRows(true);
303 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
309 LYXERR(Debug::INFO, "Buffer::~Buffer()");
310 // here the buffer should take care that it is
311 // saved properly, before it goes into the void.
313 // GuiView already destroyed
316 if (d->unnamed && d->filename.extension() == "internal") {
317 // No need to do additional cleanups for internal buffer.
322 // loop over children
323 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
324 Impl::BufferPositionMap::iterator end = d->children_positions.end();
325 for (; it != end; ++it) {
326 Buffer * child = const_cast<Buffer *>(it->first);
327 // The child buffer might have been closed already.
328 if (theBufferList().isLoaded(child))
329 theBufferList().releaseChild(this, child);
332 // clear references to children in macro tables
333 d->children_positions.clear();
334 d->position_to_children.clear();
336 if (!d->temppath.destroyDirectory()) {
337 Alert::warning(_("Could not remove temporary directory"),
338 bformat(_("Could not remove the temporary directory %1$s"),
339 from_utf8(d->temppath.absFilename())));
342 // Remove any previewed LaTeX snippets associated with this buffer.
343 thePreviews().removeLoader(*this);
349 void Buffer::changed() const
356 frontend::WorkAreaManager & Buffer::workAreaManager() const
358 LASSERT(d->wa_, /**/);
363 Text & Buffer::text() const
365 return d->inset->text();
369 Inset & Buffer::inset() const
375 BufferParams & Buffer::params()
381 BufferParams const & Buffer::params() const
387 ParagraphList & Buffer::paragraphs()
389 return text().paragraphs();
393 ParagraphList const & Buffer::paragraphs() const
395 return text().paragraphs();
399 LyXVC & Buffer::lyxvc()
405 LyXVC const & Buffer::lyxvc() const
411 string const Buffer::temppath() const
413 return d->temppath.absFilename();
417 TexRow & Buffer::texrow()
423 TexRow const & Buffer::texrow() const
429 TocBackend & Buffer::tocBackend() const
431 return d->toc_backend;
435 Undo & Buffer::undo()
441 string Buffer::latexName(bool const no_path) const
443 FileName latex_name =
444 makeLatexName(exportFileName());
445 return no_path ? latex_name.onlyFileName()
446 : latex_name.absFilename();
450 FileName Buffer::exportFileName() const
452 docstring const branch_suffix =
453 params().branchlist().getFilenameSuffix();
454 if (branch_suffix.empty())
457 string const name = fileName().onlyFileNameWithoutExt()
458 + to_utf8(branch_suffix);
459 FileName res(fileName().onlyPath().absFilename() + "/" + name);
460 res.changeExtension(fileName().extension());
466 string Buffer::logName(LogType * type) const
468 string const filename = latexName(false);
470 if (filename.empty()) {
476 string const path = temppath();
478 FileName const fname(addName(temppath(),
479 onlyFilename(changeExtension(filename,
482 // FIXME: how do we know this is the name of the build log?
483 FileName const bname(
484 addName(path, onlyFilename(
485 changeExtension(filename,
486 formats.extension(bufferFormat()) + ".out"))));
488 // Also consider the master buffer log file
489 FileName masterfname = fname;
491 if (masterBuffer() != this) {
492 string const mlogfile = masterBuffer()->logName(&mtype);
493 masterfname = FileName(mlogfile);
496 // If no Latex log or Build log is newer, show Build log
497 if (bname.exists() &&
498 ((!fname.exists() && !masterfname.exists())
499 || (fname.lastModified() < bname.lastModified()
500 && masterfname.lastModified() < bname.lastModified()))) {
501 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
504 return bname.absFilename();
505 // If we have a newer master file log or only a master log, show this
506 } else if (fname != masterfname
507 && (!fname.exists() && (masterfname.exists()
508 || fname.lastModified() < masterfname.lastModified()))) {
509 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
512 return masterfname.absFilename();
514 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
517 return fname.absFilename();
521 void Buffer::setReadonly(bool const flag)
523 if (d->read_only != flag) {
530 void Buffer::setFileName(string const & newfile)
532 d->filename = makeAbsPath(newfile);
533 setReadonly(d->filename.isReadOnly());
538 int Buffer::readHeader(Lexer & lex)
540 int unknown_tokens = 0;
542 int begin_header_line = -1;
544 // Initialize parameters that may be/go lacking in header:
545 params().branchlist().clear();
546 params().preamble.erase();
547 params().options.erase();
548 params().master.erase();
549 params().float_placement.erase();
550 params().paperwidth.erase();
551 params().paperheight.erase();
552 params().leftmargin.erase();
553 params().rightmargin.erase();
554 params().topmargin.erase();
555 params().bottommargin.erase();
556 params().headheight.erase();
557 params().headsep.erase();
558 params().footskip.erase();
559 params().columnsep.erase();
560 params().fontsCJK.erase();
561 params().listings_params.clear();
562 params().clearLayoutModules();
563 params().clearRemovedModules();
564 params().pdfoptions().clear();
565 params().indiceslist().clear();
566 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
568 for (int i = 0; i < 4; ++i) {
569 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
570 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
573 ErrorList & errorList = d->errorLists["Parse"];
582 if (token == "\\end_header")
586 if (token == "\\begin_header") {
587 begin_header_line = line;
591 LYXERR(Debug::PARSER, "Handling document header token: `"
594 string unknown = params().readToken(lex, token, d->filename.onlyPath());
595 if (!unknown.empty()) {
596 if (unknown[0] != '\\' && token == "\\textclass") {
597 Alert::warning(_("Unknown document class"),
598 bformat(_("Using the default document class, because the "
599 "class %1$s is unknown."), from_utf8(unknown)));
602 docstring const s = bformat(_("Unknown token: "
606 errorList.push_back(ErrorItem(_("Document header error"),
611 if (begin_header_line) {
612 docstring const s = _("\\begin_header is missing");
613 errorList.push_back(ErrorItem(_("Document header error"),
617 params().makeDocumentClass();
619 return unknown_tokens;
624 // changed to be public and have one parameter
625 // Returns true if "\end_document" is not read (Asger)
626 bool Buffer::readDocument(Lexer & lex)
628 ErrorList & errorList = d->errorLists["Parse"];
631 if (!lex.checkFor("\\begin_document")) {
632 docstring const s = _("\\begin_document is missing");
633 errorList.push_back(ErrorItem(_("Document header error"),
637 // we are reading in a brand new document
638 LASSERT(paragraphs().empty(), /**/);
642 if (params().outputChanges) {
643 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
644 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
645 LaTeXFeatures::isAvailable("xcolor");
647 if (!dvipost && !xcolorulem) {
648 Alert::warning(_("Changes not shown in LaTeX output"),
649 _("Changes will not be highlighted in LaTeX output, "
650 "because neither dvipost nor xcolor/ulem are installed.\n"
651 "Please install these packages or redefine "
652 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
653 } else if (!xcolorulem) {
654 Alert::warning(_("Changes not shown in LaTeX output"),
655 _("Changes will not be highlighted in LaTeX output "
656 "when using pdflatex, because xcolor and ulem are not installed.\n"
657 "Please install both packages or redefine "
658 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
662 if (!params().master.empty()) {
663 FileName const master_file = makeAbsPath(params().master,
664 onlyPath(absFileName()));
665 if (isLyXFilename(master_file.absFilename())) {
667 checkAndLoadLyXFile(master_file, true);
669 // necessary e.g. after a reload
670 // to re-register the child (bug 5873)
671 // FIXME: clean up updateMacros (here, only
672 // child registering is needed).
673 master->updateMacros();
674 // set master as master buffer, but only
675 // if we are a real child
676 if (master->isChild(this))
678 // if the master is not fully loaded
679 // it is probably just loading this
680 // child. No warning needed then.
681 else if (master->isFullyLoaded())
682 LYXERR0("The master '"
684 << "' assigned to this document ("
686 << ") does not include "
687 "this document. Ignoring the master assignment.");
693 bool const res = text().read(lex, errorList, d->inset);
696 updateMacroInstances();
701 bool Buffer::readString(string const & s)
703 params().compressed = false;
705 // remove dummy empty par
706 paragraphs().clear();
710 FileName const name = FileName::tempName("Buffer_readString");
711 switch (readFile(lex, name, true)) {
715 // We need to call lyx2lyx, so write the input to a file
716 ofstream os(name.toFilesystemEncoding().c_str());
719 return readFile(name);
729 bool Buffer::readFile(FileName const & filename)
731 FileName fname(filename);
733 params().compressed = fname.isZippedFile();
735 // remove dummy empty par
736 paragraphs().clear();
739 if (readFile(lex, fname) != success)
746 bool Buffer::isFullyLoaded() const
748 return d->file_fully_loaded;
752 void Buffer::setFullyLoaded(bool value)
754 d->file_fully_loaded = value;
758 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
761 LASSERT(!filename.empty(), /**/);
763 // the first (non-comment) token _must_ be...
764 if (!lex.checkFor("\\lyxformat")) {
765 Alert::error(_("Document format failure"),
766 bformat(_("%1$s is not a readable LyX document."),
767 from_utf8(filename.absFilename())));
773 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
774 // if present remove ".," from string.
775 size_t dot = tmp_format.find_first_of(".,");
776 //lyxerr << " dot found at " << dot << endl;
777 if (dot != string::npos)
778 tmp_format.erase(dot, 1);
779 int const file_format = convert<int>(tmp_format);
780 //lyxerr << "format: " << file_format << endl;
782 // save timestamp and checksum of the original disk file, making sure
783 // to not overwrite them with those of the file created in the tempdir
784 // when it has to be converted to the current format.
786 // Save the timestamp and checksum of disk file. If filename is an
787 // emergency file, save the timestamp and checksum of the original lyx file
788 // because isExternallyModified will check for this file. (BUG4193)
789 string diskfile = filename.absFilename();
790 if (suffixIs(diskfile, ".emergency"))
791 diskfile = diskfile.substr(0, diskfile.size() - 10);
792 saveCheckSum(FileName(diskfile));
795 if (file_format != LYX_FORMAT) {
798 // lyx2lyx would fail
801 FileName const tmpfile = FileName::tempName("Buffer_readFile");
802 if (tmpfile.empty()) {
803 Alert::error(_("Conversion failed"),
804 bformat(_("%1$s is from a different"
805 " version of LyX, but a temporary"
806 " file for converting it could"
808 from_utf8(filename.absFilename())));
811 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
812 if (lyx2lyx.empty()) {
813 Alert::error(_("Conversion script not found"),
814 bformat(_("%1$s is from a different"
815 " version of LyX, but the"
816 " conversion script lyx2lyx"
817 " could not be found."),
818 from_utf8(filename.absFilename())));
821 ostringstream command;
822 command << os::python()
823 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
824 << " -t " << convert<string>(LYX_FORMAT)
825 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
826 << ' ' << quoteName(filename.toFilesystemEncoding());
827 string const command_str = command.str();
829 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
831 cmd_ret const ret = runCommand(command_str);
832 if (ret.first != 0) {
833 Alert::error(_("Conversion script failed"),
834 bformat(_("%1$s is from a different version"
835 " of LyX, but the lyx2lyx script"
836 " failed to convert it."),
837 from_utf8(filename.absFilename())));
840 bool const ret = readFile(tmpfile);
841 // Do stuff with tmpfile name and buffer name here.
842 return ret ? success : failure;
847 if (readDocument(lex)) {
848 Alert::error(_("Document format failure"),
849 bformat(_("%1$s ended unexpectedly, which means"
850 " that it is probably corrupted."),
851 from_utf8(filename.absFilename())));
854 d->file_fully_loaded = true;
859 // Should probably be moved to somewhere else: BufferView? LyXView?
860 bool Buffer::save() const
862 // We don't need autosaves in the immediate future. (Asger)
863 resetAutosaveTimers();
865 string const encodedFilename = d->filename.toFilesystemEncoding();
868 bool madeBackup = false;
870 // make a backup if the file already exists
871 if (lyxrc.make_backup && fileName().exists()) {
872 backupName = FileName(absFileName() + '~');
873 if (!lyxrc.backupdir_path.empty()) {
874 string const mangledName =
875 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
876 backupName = FileName(addName(lyxrc.backupdir_path,
879 if (fileName().copyTo(backupName)) {
882 Alert::error(_("Backup failure"),
883 bformat(_("Cannot create backup file %1$s.\n"
884 "Please check whether the directory exists and is writeable."),
885 from_utf8(backupName.absFilename())));
886 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
890 // ask if the disk file has been externally modified (use checksum method)
891 if (fileName().exists() && isExternallyModified(checksum_method)) {
892 docstring const file = makeDisplayPath(absFileName(), 20);
893 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
894 "you want to overwrite this file?"), file);
895 int const ret = Alert::prompt(_("Overwrite modified file?"),
896 text, 1, 1, _("&Overwrite"), _("&Cancel"));
901 if (writeFile(d->filename)) {
905 // Saving failed, so backup is not backup
907 backupName.moveTo(d->filename);
913 bool Buffer::writeFile(FileName const & fname) const
915 if (d->read_only && fname == d->filename)
920 docstring const str = bformat(_("Saving document %1$s..."),
921 makeDisplayPath(fname.absFilename()));
924 if (params().compressed) {
925 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
926 retval = ofs && write(ofs);
928 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
929 retval = ofs && write(ofs);
933 message(str + _(" could not write file!"));
937 removeAutosaveFile();
939 saveCheckSum(d->filename);
940 message(str + _(" done."));
946 bool Buffer::write(ostream & ofs) const
949 // Use the standard "C" locale for file output.
950 ofs.imbue(locale::classic());
953 // The top of the file should not be written by params().
955 // write out a comment in the top of the file
956 ofs << "#LyX " << lyx_version
957 << " created this file. For more info see http://www.lyx.org/\n"
958 << "\\lyxformat " << LYX_FORMAT << "\n"
959 << "\\begin_document\n";
961 /// For each author, set 'used' to true if there is a change
962 /// by this author in the document; otherwise set it to 'false'.
963 AuthorList::Authors::const_iterator a_it = params().authors().begin();
964 AuthorList::Authors::const_iterator a_end = params().authors().end();
965 for (; a_it != a_end; ++a_it)
966 a_it->setUsed(false);
968 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
969 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
970 for ( ; it != end; ++it)
971 it->checkAuthors(params().authors());
973 // now write out the buffer parameters.
974 ofs << "\\begin_header\n";
975 params().writeFile(ofs);
976 ofs << "\\end_header\n";
979 ofs << "\n\\begin_body\n";
981 ofs << "\n\\end_body\n";
983 // Write marker that shows file is complete
984 ofs << "\\end_document" << endl;
986 // Shouldn't really be needed....
989 // how to check if close went ok?
990 // Following is an attempt... (BE 20001011)
992 // good() returns false if any error occured, including some
994 // bad() returns true if something bad happened in the buffer,
995 // which should include file system full errors.
1000 lyxerr << "File was not closed properly." << endl;
1007 bool Buffer::makeLaTeXFile(FileName const & fname,
1008 string const & original_path,
1009 OutputParams const & runparams_in,
1010 bool output_preamble, bool output_body) const
1012 OutputParams runparams = runparams_in;
1013 if (params().useXetex)
1014 runparams.flavor = OutputParams::XETEX;
1016 string const encoding = runparams.encoding->iconvName();
1017 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1020 try { ofs.reset(encoding); }
1021 catch (iconv_codecvt_facet_exception & e) {
1022 lyxerr << "Caught iconv exception: " << e.what() << endl;
1023 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1024 "verify that the support software for your encoding (%1$s) is "
1025 "properly installed"), from_ascii(encoding)));
1028 if (!openFileWrite(ofs, fname))
1031 //TexStream ts(ofs.rdbuf(), &texrow());
1032 ErrorList & errorList = d->errorLists["Export"];
1034 bool failed_export = false;
1037 writeLaTeXSource(ofs, original_path,
1038 runparams, output_preamble, output_body);
1040 catch (EncodingException & e) {
1041 odocstringstream ods;
1042 ods.put(e.failed_char);
1044 oss << "0x" << hex << e.failed_char << dec;
1045 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1046 " (code point %2$s)"),
1047 ods.str(), from_utf8(oss.str()));
1048 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1049 "representable in the chosen encoding.\n"
1050 "Changing the document encoding to utf8 could help."),
1051 e.par_id, e.pos, e.pos + 1));
1052 failed_export = true;
1054 catch (iconv_codecvt_facet_exception & e) {
1055 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1056 _(e.what()), -1, 0, 0));
1057 failed_export = true;
1059 catch (exception const & e) {
1060 errorList.push_back(ErrorItem(_("conversion failed"),
1061 _(e.what()), -1, 0, 0));
1062 failed_export = true;
1065 lyxerr << "Caught some really weird exception..." << endl;
1071 failed_export = true;
1072 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1076 return !failed_export;
1080 void Buffer::writeLaTeXSource(odocstream & os,
1081 string const & original_path,
1082 OutputParams const & runparams_in,
1083 bool const output_preamble, bool const output_body) const
1085 // The child documents, if any, shall be already loaded at this point.
1087 OutputParams runparams = runparams_in;
1089 // Classify the unicode characters appearing in math insets
1090 Encodings::initUnicodeMath(*this);
1092 // validate the buffer.
1093 LYXERR(Debug::LATEX, " Validating buffer...");
1094 LaTeXFeatures features(*this, params(), runparams);
1096 LYXERR(Debug::LATEX, " Buffer validation done.");
1098 // The starting paragraph of the coming rows is the
1099 // first paragraph of the document. (Asger)
1100 if (output_preamble && runparams.nice) {
1101 os << "%% LyX " << lyx_version << " created this file. "
1102 "For more info, see http://www.lyx.org/.\n"
1103 "%% Do not edit unless you really know what "
1105 d->texrow.newline();
1106 d->texrow.newline();
1108 LYXERR(Debug::INFO, "lyx document header finished");
1110 // Don't move this behind the parent_buffer=0 code below,
1111 // because then the macros will not get the right "redefinition"
1112 // flag as they don't see the parent macros which are output before.
1115 // fold macros if possible, still with parent buffer as the
1116 // macros will be put in the prefix anyway.
1117 updateMacroInstances();
1119 // There are a few differences between nice LaTeX and usual files:
1120 // usual is \batchmode and has a
1121 // special input@path to allow the including of figures
1122 // with either \input or \includegraphics (what figinsets do).
1123 // input@path is set when the actual parameter
1124 // original_path is set. This is done for usual tex-file, but not
1125 // for nice-latex-file. (Matthias 250696)
1126 // Note that input@path is only needed for something the user does
1127 // in the preamble, included .tex files or ERT, files included by
1128 // LyX work without it.
1129 if (output_preamble) {
1130 if (!runparams.nice) {
1131 // code for usual, NOT nice-latex-file
1132 os << "\\batchmode\n"; // changed
1133 // from \nonstopmode
1134 d->texrow.newline();
1136 if (!original_path.empty()) {
1138 // We don't know the encoding of inputpath
1139 docstring const inputpath = from_utf8(latex_path(original_path));
1140 os << "\\makeatletter\n"
1141 << "\\def\\input@path{{"
1142 << inputpath << "/}}\n"
1143 << "\\makeatother\n";
1144 d->texrow.newline();
1145 d->texrow.newline();
1146 d->texrow.newline();
1149 // get parent macros (if this buffer has a parent) which will be
1150 // written at the document begin further down.
1151 MacroSet parentMacros;
1152 listParentMacros(parentMacros, features);
1154 // Write the preamble
1155 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1157 runparams.use_japanese = features.isRequired("japanese");
1163 os << "\\begin{document}\n";
1164 d->texrow.newline();
1166 // output the parent macros
1167 MacroSet::iterator it = parentMacros.begin();
1168 MacroSet::iterator end = parentMacros.end();
1169 for (; it != end; ++it)
1170 (*it)->write(os, true);
1171 } // output_preamble
1173 d->texrow.start(paragraphs().begin()->id(), 0);
1175 LYXERR(Debug::INFO, "preamble finished, now the body.");
1177 // if we are doing a real file with body, even if this is the
1178 // child of some other buffer, let's cut the link here.
1179 // This happens for example if only a child document is printed.
1180 Buffer const * save_parent = 0;
1181 if (output_preamble) {
1182 save_parent = d->parent();
1187 latexParagraphs(*this, text(), os, d->texrow, runparams);
1189 // Restore the parenthood if needed
1190 if (output_preamble)
1191 d->setParent(save_parent);
1193 // add this just in case after all the paragraphs
1195 d->texrow.newline();
1197 if (output_preamble) {
1198 os << "\\end{document}\n";
1199 d->texrow.newline();
1200 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1202 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1204 runparams_in.encoding = runparams.encoding;
1206 // Just to be sure. (Asger)
1207 d->texrow.newline();
1209 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1210 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1214 bool Buffer::isLatex() const
1216 return params().documentClass().outputType() == LATEX;
1220 bool Buffer::isLiterate() const
1222 return params().documentClass().outputType() == LITERATE;
1226 bool Buffer::isDocBook() const
1228 return params().documentClass().outputType() == DOCBOOK;
1232 void Buffer::makeDocBookFile(FileName const & fname,
1233 OutputParams const & runparams,
1234 bool const body_only) const
1236 LYXERR(Debug::LATEX, "makeDocBookFile...");
1239 if (!openFileWrite(ofs, fname))
1242 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1246 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1250 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1251 OutputParams const & runparams,
1252 bool const only_body) const
1254 LaTeXFeatures features(*this, params(), runparams);
1259 DocumentClass const & tclass = params().documentClass();
1260 string const top_element = tclass.latexname();
1263 if (runparams.flavor == OutputParams::XML)
1264 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1267 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1270 if (! tclass.class_header().empty())
1271 os << from_ascii(tclass.class_header());
1272 else if (runparams.flavor == OutputParams::XML)
1273 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1274 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1276 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1278 docstring preamble = from_utf8(params().preamble);
1279 if (runparams.flavor != OutputParams::XML ) {
1280 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1281 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1282 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1283 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1286 string const name = runparams.nice
1287 ? changeExtension(absFileName(), ".sgml") : fname;
1288 preamble += features.getIncludedFiles(name);
1289 preamble += features.getLyXSGMLEntities();
1291 if (!preamble.empty()) {
1292 os << "\n [ " << preamble << " ]";
1297 string top = top_element;
1299 if (runparams.flavor == OutputParams::XML)
1300 top += params().language->code();
1302 top += params().language->code().substr(0, 2);
1305 if (!params().options.empty()) {
1307 top += params().options;
1310 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1311 << " file was created by LyX " << lyx_version
1312 << "\n See http://www.lyx.org/ for more information -->\n";
1314 params().documentClass().counters().reset();
1318 sgml::openTag(os, top);
1320 docbookParagraphs(paragraphs(), *this, os, runparams);
1321 sgml::closeTag(os, top_element);
1325 void Buffer::makeLyXHTMLFile(FileName const & fname,
1326 OutputParams const & runparams,
1327 bool const body_only) const
1329 LYXERR(Debug::LATEX, "makeLYXHTMLFile...");
1332 if (!openFileWrite(ofs, fname))
1335 writeLyXHTMLSource(ofs, runparams, body_only);
1339 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1343 void Buffer::writeLyXHTMLSource(odocstream & os,
1344 OutputParams const & runparams,
1345 bool const only_body) const
1347 LaTeXFeatures features(*this, params(), runparams);
1353 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" <<
1354 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1355 // FIXME Language should be set properly.
1356 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n";
1359 // FIXME Presumably need to set this right
1360 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1361 // FIXME Get this during validation? What about other meta-data?
1362 os << "<title>TBA</title>\n";
1364 os << features.getTClassHTMLPreamble();
1368 docstring const styleinfo = features.getTClassHTMLStyles();
1369 if (!styleinfo.empty()) {
1370 os << "<style type='text/css'>\n";
1374 os << "</head>\n<body>\n";
1377 params().documentClass().counters().reset();
1378 xhtmlParagraphs(paragraphs(), *this, os, runparams);
1380 os << "</body>\n</html>\n";
1384 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1385 // Other flags: -wall -v0 -x
1386 int Buffer::runChktex()
1390 // get LaTeX-Filename
1391 FileName const path(temppath());
1392 string const name = addName(path.absFilename(), latexName());
1393 string const org_path = filePath();
1395 PathChanger p(path); // path to LaTeX file
1396 message(_("Running chktex..."));
1398 // Generate the LaTeX file if neccessary
1399 OutputParams runparams(¶ms().encoding());
1400 runparams.flavor = OutputParams::LATEX;
1401 runparams.nice = false;
1402 makeLaTeXFile(FileName(name), org_path, runparams);
1405 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1406 int const res = chktex.run(terr); // run chktex
1409 Alert::error(_("chktex failure"),
1410 _("Could not run chktex successfully."));
1411 } else if (res > 0) {
1412 ErrorList & errlist = d->errorLists["ChkTeX"];
1414 bufferErrors(terr, errlist);
1425 void Buffer::validate(LaTeXFeatures & features) const
1427 params().validate(features);
1431 for_each(paragraphs().begin(), paragraphs().end(),
1432 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1434 if (lyxerr.debugging(Debug::LATEX)) {
1435 features.showStruct();
1440 void Buffer::getLabelList(vector<docstring> & list) const
1442 // If this is a child document, use the parent's list instead.
1443 Buffer const * const pbuf = d->parent();
1445 pbuf->getLabelList(list);
1450 Toc & toc = d->toc_backend.toc("label");
1451 TocIterator toc_it = toc.begin();
1452 TocIterator end = toc.end();
1453 for (; toc_it != end; ++toc_it) {
1454 if (toc_it->depth() == 0)
1455 list.push_back(toc_it->str());
1460 void Buffer::updateBibfilesCache(UpdateScope scope) const
1462 // If this is a child document, use the parent's cache instead.
1463 Buffer const * const pbuf = d->parent();
1464 if (pbuf && scope != UpdateChildOnly) {
1465 pbuf->updateBibfilesCache();
1469 d->bibfilesCache_.clear();
1470 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1471 if (it->lyxCode() == BIBTEX_CODE) {
1472 InsetBibtex const & inset =
1473 static_cast<InsetBibtex const &>(*it);
1474 support::FileNameList const bibfiles = inset.getBibFiles();
1475 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1478 } else if (it->lyxCode() == INCLUDE_CODE) {
1479 InsetInclude & inset =
1480 static_cast<InsetInclude &>(*it);
1481 inset.updateBibfilesCache();
1482 support::FileNameList const & bibfiles =
1483 inset.getBibfilesCache();
1484 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1489 // the bibinfo cache is now invalid
1490 d->bibinfoCacheValid_ = false;
1494 void Buffer::invalidateBibinfoCache()
1496 d->bibinfoCacheValid_ = false;
1500 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1502 // If this is a child document, use the parent's cache instead.
1503 Buffer const * const pbuf = d->parent();
1504 if (pbuf && scope != UpdateChildOnly)
1505 return pbuf->getBibfilesCache();
1507 // We update the cache when first used instead of at loading time.
1508 if (d->bibfilesCache_.empty())
1509 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1511 return d->bibfilesCache_;
1515 BiblioInfo const & Buffer::masterBibInfo() const
1517 // if this is a child document and the parent is already loaded
1518 // use the parent's list instead [ale990412]
1519 Buffer const * const tmp = masterBuffer();
1522 return tmp->masterBibInfo();
1523 return localBibInfo();
1527 BiblioInfo const & Buffer::localBibInfo() const
1529 if (d->bibinfoCacheValid_) {
1530 support::FileNameList const & bibfilesCache = getBibfilesCache();
1531 // compare the cached timestamps with the actual ones.
1532 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1533 support::FileNameList::const_iterator en = bibfilesCache.end();
1534 for (; ei != en; ++ ei) {
1535 time_t lastw = ei->lastModified();
1536 if (lastw != d->bibfileStatus_[*ei]) {
1537 d->bibinfoCacheValid_ = false;
1538 d->bibfileStatus_[*ei] = lastw;
1544 if (!d->bibinfoCacheValid_) {
1545 d->bibinfo_.clear();
1546 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1547 it->fillWithBibKeys(d->bibinfo_, it);
1548 d->bibinfoCacheValid_ = true;
1554 bool Buffer::isDepClean(string const & name) const
1556 DepClean::const_iterator const it = d->dep_clean.find(name);
1557 if (it == d->dep_clean.end())
1563 void Buffer::markDepClean(string const & name)
1565 d->dep_clean[name] = true;
1569 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1571 switch (cmd.action) {
1572 case LFUN_BUFFER_EXPORT: {
1573 docstring const arg = cmd.argument();
1574 bool enable = arg == "custom" || isExportable(to_utf8(arg));
1576 flag.message(bformat(
1577 _("Don't know how to export to format: %1$s"), arg));
1578 flag.setEnabled(enable);
1582 case LFUN_BRANCH_ACTIVATE:
1583 case LFUN_BRANCH_DEACTIVATE: {
1584 BranchList const & branchList = params().branchlist();
1585 docstring const branchName = cmd.argument();
1586 flag.setEnabled(!branchName.empty()
1587 && branchList.find(branchName));
1591 case LFUN_BRANCH_ADD:
1592 case LFUN_BRANCHES_RENAME:
1593 case LFUN_BUFFER_PRINT:
1594 // if no Buffer is present, then of course we won't be called!
1595 flag.setEnabled(true);
1605 void Buffer::dispatch(string const & command, DispatchResult & result)
1607 return dispatch(lyxaction.lookupFunc(command), result);
1611 // NOTE We can end up here even if we have no GUI, because we are called
1612 // by LyX::exec to handled command-line requests. So we may need to check
1613 // whether we have a GUI or not. The boolean use_gui holds this information.
1614 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1616 // We'll set this back to false if need be.
1617 bool dispatched = true;
1619 switch (func.action) {
1620 case LFUN_BUFFER_EXPORT: {
1621 bool success = doExport(to_utf8(func.argument()), false);
1622 dr.setError(success);
1624 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1629 case LFUN_BRANCH_ADD: {
1630 BranchList & branchList = params().branchlist();
1631 docstring const branchName = func.argument();
1632 if (branchName.empty()) {
1636 Branch * branch = branchList.find(branchName);
1638 LYXERR0("Branch " << branchName << " does already exist.");
1640 docstring const msg =
1641 bformat(_("Branch \"%1$s\" does already exist."), branchName);
1644 branchList.add(branchName);
1646 dr.update(Update::Force);
1651 case LFUN_BRANCH_ACTIVATE:
1652 case LFUN_BRANCH_DEACTIVATE: {
1653 BranchList & branchList = params().branchlist();
1654 docstring const branchName = func.argument();
1655 // the case without a branch name is handled elsewhere
1656 if (branchName.empty()) {
1660 Branch * branch = branchList.find(branchName);
1662 LYXERR0("Branch " << branchName << " does not exist.");
1664 docstring const msg =
1665 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1668 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1670 dr.update(Update::Force);
1675 case LFUN_BRANCHES_RENAME: {
1676 if (func.argument().empty())
1679 docstring const oldname = from_utf8(func.getArg(0));
1680 docstring const newname = from_utf8(func.getArg(1));
1681 InsetIterator it = inset_iterator_begin(inset());
1682 InsetIterator const end = inset_iterator_end(inset());
1683 bool success = false;
1684 for (; it != end; ++it) {
1685 if (it->lyxCode() == BRANCH_CODE) {
1686 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1687 if (ins.branch() == oldname) {
1688 undo().recordUndo(it);
1689 ins.rename(newname);
1694 if (it->lyxCode() == INCLUDE_CODE) {
1695 // get buffer of external file
1696 InsetInclude const & ins =
1697 static_cast<InsetInclude const &>(*it);
1698 Buffer * child = ins.getChildBuffer();
1701 child->dispatch(func, dr);
1706 dr.update(Update::Force);
1710 case LFUN_BUFFER_PRINT: {
1711 // we'll assume there's a problem until we succeed
1713 string target = func.getArg(0);
1714 string target_name = func.getArg(1);
1715 string command = func.getArg(2);
1718 || target_name.empty()
1719 || command.empty()) {
1720 LYXERR0("Unable to parse " << func.argument());
1721 docstring const msg =
1722 bformat(_("Unable to parse \"%1$s\""), func.argument());
1726 if (target != "printer" && target != "file") {
1727 LYXERR0("Unrecognized target \"" << target << '"');
1728 docstring const msg =
1729 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1734 if (!doExport("dvi", true)) {
1735 showPrintError(absFileName());
1736 dr.setMessage(_("Error exporting to DVI."));
1740 // Push directory path.
1741 string const path = temppath();
1742 // Prevent the compiler from optimizing away p
1746 // there are three cases here:
1747 // 1. we print to a file
1748 // 2. we print directly to a printer
1749 // 3. we print using a spool command (print to file first)
1752 string const dviname = changeExtension(latexName(true), "dvi");
1754 if (target == "printer") {
1755 if (!lyxrc.print_spool_command.empty()) {
1756 // case 3: print using a spool
1757 string const psname = changeExtension(dviname,".ps");
1758 command += ' ' + lyxrc.print_to_file
1761 + quoteName(dviname);
1763 string command2 = lyxrc.print_spool_command + ' ';
1764 if (target_name != "default") {
1765 command2 += lyxrc.print_spool_printerprefix
1769 command2 += quoteName(psname);
1771 // If successful, then spool command
1772 res = one.startscript(Systemcall::Wait, command);
1775 // If there's no GUI, we have to wait on this command. Otherwise,
1776 // LyX deletes the temporary directory, and with it the spooled
1777 // file, before it can be printed!!
1778 Systemcall::Starttype stype = use_gui ?
1779 Systemcall::DontWait : Systemcall::Wait;
1780 res = one.startscript(stype, command2);
1783 // case 2: print directly to a printer
1784 if (target_name != "default")
1785 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1787 Systemcall::Starttype stype = use_gui ?
1788 Systemcall::DontWait : Systemcall::Wait;
1789 res = one.startscript(stype, command + quoteName(dviname));
1793 // case 1: print to a file
1794 FileName const filename(makeAbsPath(target_name, filePath()));
1795 FileName const dvifile(makeAbsPath(dviname, path));
1796 if (filename.exists()) {
1797 docstring text = bformat(
1798 _("The file %1$s already exists.\n\n"
1799 "Do you want to overwrite that file?"),
1800 makeDisplayPath(filename.absFilename()));
1801 if (Alert::prompt(_("Overwrite file?"),
1802 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1805 command += ' ' + lyxrc.print_to_file
1806 + quoteName(filename.toFilesystemEncoding())
1808 + quoteName(dvifile.toFilesystemEncoding());
1810 Systemcall::Starttype stype = use_gui ?
1811 Systemcall::DontWait : Systemcall::Wait;
1812 res = one.startscript(stype, command);
1818 dr.setMessage(_("Error running external commands."));
1819 showPrintError(absFileName());
1828 dr.dispatched(dispatched);
1832 void Buffer::changeLanguage(Language const * from, Language const * to)
1834 LASSERT(from, /**/);
1837 for_each(par_iterator_begin(),
1839 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1843 bool Buffer::isMultiLingual() const
1845 ParConstIterator end = par_iterator_end();
1846 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1847 if (it->isMultiLingual(params()))
1854 DocIterator Buffer::getParFromID(int const id) const
1856 Buffer * buf = const_cast<Buffer *>(this);
1858 // John says this is called with id == -1 from undo
1859 lyxerr << "getParFromID(), id: " << id << endl;
1860 return doc_iterator_end(buf);
1863 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1864 if (it.paragraph().id() == id)
1867 return doc_iterator_end(buf);
1871 bool Buffer::hasParWithID(int const id) const
1873 return !getParFromID(id).atEnd();
1877 ParIterator Buffer::par_iterator_begin()
1879 return ParIterator(doc_iterator_begin(this));
1883 ParIterator Buffer::par_iterator_end()
1885 return ParIterator(doc_iterator_end(this));
1889 ParConstIterator Buffer::par_iterator_begin() const
1891 return ParConstIterator(doc_iterator_begin(this));
1895 ParConstIterator Buffer::par_iterator_end() const
1897 return ParConstIterator(doc_iterator_end(this));
1901 Language const * Buffer::language() const
1903 return params().language;
1907 docstring const Buffer::B_(string const & l10n) const
1909 return params().B_(l10n);
1913 bool Buffer::isClean() const
1915 return d->lyx_clean;
1919 bool Buffer::isBakClean() const
1921 return d->bak_clean;
1925 bool Buffer::isExternallyModified(CheckMethod method) const
1927 LASSERT(d->filename.exists(), /**/);
1928 // if method == timestamp, check timestamp before checksum
1929 return (method == checksum_method
1930 || d->timestamp_ != d->filename.lastModified())
1931 && d->checksum_ != d->filename.checksum();
1935 void Buffer::saveCheckSum(FileName const & file) const
1937 if (file.exists()) {
1938 d->timestamp_ = file.lastModified();
1939 d->checksum_ = file.checksum();
1941 // in the case of save to a new file.
1948 void Buffer::markClean() const
1950 if (!d->lyx_clean) {
1951 d->lyx_clean = true;
1954 // if the .lyx file has been saved, we don't need an
1956 d->bak_clean = true;
1960 void Buffer::markBakClean() const
1962 d->bak_clean = true;
1966 void Buffer::setUnnamed(bool flag)
1972 bool Buffer::isUnnamed() const
1978 // FIXME: this function should be moved to buffer_pimpl.C
1979 void Buffer::markDirty()
1982 d->lyx_clean = false;
1985 d->bak_clean = false;
1987 DepClean::iterator it = d->dep_clean.begin();
1988 DepClean::const_iterator const end = d->dep_clean.end();
1990 for (; it != end; ++it)
1995 FileName Buffer::fileName() const
2001 string Buffer::absFileName() const
2003 return d->filename.absFilename();
2007 string Buffer::filePath() const
2009 return d->filename.onlyPath().absFilename() + "/";
2013 bool Buffer::isReadonly() const
2015 return d->read_only;
2019 void Buffer::setParent(Buffer const * buffer)
2021 // Avoids recursive include.
2022 d->setParent(buffer == this ? 0 : buffer);
2027 Buffer const * Buffer::parent() const
2033 void Buffer::collectRelatives(BufferSet & bufs) const
2037 parent()->collectRelatives(bufs);
2039 // loop over children
2040 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2041 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2042 for (; it != end; ++it)
2043 bufs.insert(const_cast<Buffer *>(it->first));
2047 std::vector<Buffer const *> Buffer::allRelatives() const
2050 collectRelatives(bufs);
2051 BufferSet::iterator it = bufs.begin();
2052 std::vector<Buffer const *> ret;
2053 for (; it != bufs.end(); ++it)
2059 Buffer const * Buffer::masterBuffer() const
2061 Buffer const * const pbuf = d->parent();
2065 return pbuf->masterBuffer();
2069 bool Buffer::isChild(Buffer * child) const
2071 return d->children_positions.find(child) != d->children_positions.end();
2075 DocIterator Buffer::firstChildPosition(Buffer const * child)
2077 Impl::BufferPositionMap::iterator it;
2078 it = d->children_positions.find(child);
2079 if (it == d->children_positions.end())
2080 return DocIterator(this);
2085 std::vector<Buffer *> Buffer::getChildren() const
2087 std::vector<Buffer *> clist;
2088 // loop over children
2089 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2090 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2091 for (; it != end; ++it) {
2092 Buffer * child = const_cast<Buffer *>(it->first);
2093 clist.push_back(child);
2094 // there might be grandchildren
2095 std::vector<Buffer *> glist = child->getChildren();
2096 for (vector<Buffer *>::const_iterator git = glist.begin();
2097 git != glist.end(); ++git)
2098 clist.push_back(*git);
2104 template<typename M>
2105 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2110 typename M::iterator it = m.lower_bound(x);
2111 if (it == m.begin())
2119 MacroData const * Buffer::getBufferMacro(docstring const & name,
2120 DocIterator const & pos) const
2122 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2124 // if paragraphs have no macro context set, pos will be empty
2128 // we haven't found anything yet
2129 DocIterator bestPos = par_iterator_begin();
2130 MacroData const * bestData = 0;
2132 // find macro definitions for name
2133 Impl::NamePositionScopeMacroMap::iterator nameIt
2134 = d->macros.find(name);
2135 if (nameIt != d->macros.end()) {
2136 // find last definition in front of pos or at pos itself
2137 Impl::PositionScopeMacroMap::const_iterator it
2138 = greatest_below(nameIt->second, pos);
2139 if (it != nameIt->second.end()) {
2141 // scope ends behind pos?
2142 if (pos < it->second.first) {
2143 // Looks good, remember this. If there
2144 // is no external macro behind this,
2145 // we found the right one already.
2146 bestPos = it->first;
2147 bestData = &it->second.second;
2151 // try previous macro if there is one
2152 if (it == nameIt->second.begin())
2159 // find macros in included files
2160 Impl::PositionScopeBufferMap::const_iterator it
2161 = greatest_below(d->position_to_children, pos);
2162 if (it == d->position_to_children.end())
2163 // no children before
2167 // do we know something better (i.e. later) already?
2168 if (it->first < bestPos )
2171 // scope ends behind pos?
2172 if (pos < it->second.first) {
2173 // look for macro in external file
2174 d->macro_lock = true;
2175 MacroData const * data
2176 = it->second.second->getMacro(name, false);
2177 d->macro_lock = false;
2179 bestPos = it->first;
2185 // try previous file if there is one
2186 if (it == d->position_to_children.begin())
2191 // return the best macro we have found
2196 MacroData const * Buffer::getMacro(docstring const & name,
2197 DocIterator const & pos, bool global) const
2202 // query buffer macros
2203 MacroData const * data = getBufferMacro(name, pos);
2207 // If there is a master buffer, query that
2208 Buffer const * const pbuf = d->parent();
2210 d->macro_lock = true;
2211 MacroData const * macro = pbuf->getMacro(
2212 name, *this, false);
2213 d->macro_lock = false;
2219 data = MacroTable::globalMacros().get(name);
2228 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2230 // set scope end behind the last paragraph
2231 DocIterator scope = par_iterator_begin();
2232 scope.pit() = scope.lastpit() + 1;
2234 return getMacro(name, scope, global);
2238 MacroData const * Buffer::getMacro(docstring const & name,
2239 Buffer const & child, bool global) const
2241 // look where the child buffer is included first
2242 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2243 if (it == d->children_positions.end())
2246 // check for macros at the inclusion position
2247 return getMacro(name, it->second, global);
2251 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2253 pit_type lastpit = it.lastpit();
2255 // look for macros in each paragraph
2256 while (it.pit() <= lastpit) {
2257 Paragraph & par = it.paragraph();
2259 // iterate over the insets of the current paragraph
2260 InsetList const & insets = par.insetList();
2261 InsetList::const_iterator iit = insets.begin();
2262 InsetList::const_iterator end = insets.end();
2263 for (; iit != end; ++iit) {
2264 it.pos() = iit->pos;
2266 // is it a nested text inset?
2267 if (iit->inset->asInsetText()) {
2268 // Inset needs its own scope?
2269 InsetText const * itext = iit->inset->asInsetText();
2270 bool newScope = itext->isMacroScope();
2272 // scope which ends just behind the inset
2273 DocIterator insetScope = it;
2276 // collect macros in inset
2277 it.push_back(CursorSlice(*iit->inset));
2278 updateMacros(it, newScope ? insetScope : scope);
2283 // is it an external file?
2284 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2285 // get buffer of external file
2286 InsetInclude const & inset =
2287 static_cast<InsetInclude const &>(*iit->inset);
2288 d->macro_lock = true;
2289 Buffer * child = inset.getChildBuffer();
2290 d->macro_lock = false;
2294 // register its position, but only when it is
2295 // included first in the buffer
2296 if (d->children_positions.find(child) ==
2297 d->children_positions.end())
2298 d->children_positions[child] = it;
2300 // register child with its scope
2301 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2305 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2309 MathMacroTemplate & macroTemplate =
2310 static_cast<MathMacroTemplate &>(*iit->inset);
2311 MacroContext mc(*this, it);
2312 macroTemplate.updateToContext(mc);
2315 bool valid = macroTemplate.validMacro();
2316 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2317 // then the BufferView's cursor will be invalid in
2318 // some cases which leads to crashes.
2323 d->macros[macroTemplate.name()][it] =
2324 Impl::ScopeMacro(scope, MacroData(*this, it));
2334 void Buffer::updateMacros() const
2339 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2341 // start with empty table
2343 d->children_positions.clear();
2344 d->position_to_children.clear();
2346 // Iterate over buffer, starting with first paragraph
2347 // The scope must be bigger than any lookup DocIterator
2348 // later. For the global lookup, lastpit+1 is used, hence
2349 // we use lastpit+2 here.
2350 DocIterator it = par_iterator_begin();
2351 DocIterator outerScope = it;
2352 outerScope.pit() = outerScope.lastpit() + 2;
2353 updateMacros(it, outerScope);
2357 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2359 InsetIterator it = inset_iterator_begin(inset());
2360 InsetIterator const end = inset_iterator_end(inset());
2361 for (; it != end; ++it) {
2362 if (it->lyxCode() == BRANCH_CODE) {
2363 InsetBranch & br = static_cast<InsetBranch &>(*it);
2364 docstring const name = br.branch();
2365 if (!from_master && !params().branchlist().find(name))
2366 result.push_back(name);
2367 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2368 result.push_back(name);
2371 if (it->lyxCode() == INCLUDE_CODE) {
2372 // get buffer of external file
2373 InsetInclude const & ins =
2374 static_cast<InsetInclude const &>(*it);
2375 Buffer * child = ins.getChildBuffer();
2378 child->getUsedBranches(result, true);
2381 // remove duplicates
2386 void Buffer::updateMacroInstances() const
2388 LYXERR(Debug::MACROS, "updateMacroInstances for "
2389 << d->filename.onlyFileName());
2390 DocIterator it = doc_iterator_begin(this);
2391 DocIterator end = doc_iterator_end(this);
2392 for (; it != end; it.forwardPos()) {
2393 // look for MathData cells in InsetMathNest insets
2394 Inset * inset = it.nextInset();
2398 InsetMath * minset = inset->asInsetMath();
2402 // update macro in all cells of the InsetMathNest
2403 DocIterator::idx_type n = minset->nargs();
2404 MacroContext mc = MacroContext(*this, it);
2405 for (DocIterator::idx_type i = 0; i < n; ++i) {
2406 MathData & data = minset->cell(i);
2407 data.updateMacros(0, mc);
2413 void Buffer::listMacroNames(MacroNameSet & macros) const
2418 d->macro_lock = true;
2420 // loop over macro names
2421 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2422 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2423 for (; nameIt != nameEnd; ++nameIt)
2424 macros.insert(nameIt->first);
2426 // loop over children
2427 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2428 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2429 for (; it != end; ++it)
2430 it->first->listMacroNames(macros);
2433 Buffer const * const pbuf = d->parent();
2435 pbuf->listMacroNames(macros);
2437 d->macro_lock = false;
2441 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2443 Buffer const * const pbuf = d->parent();
2448 pbuf->listMacroNames(names);
2451 MacroNameSet::iterator it = names.begin();
2452 MacroNameSet::iterator end = names.end();
2453 for (; it != end; ++it) {
2455 MacroData const * data =
2456 pbuf->getMacro(*it, *this, false);
2458 macros.insert(data);
2460 // we cannot access the original MathMacroTemplate anymore
2461 // here to calls validate method. So we do its work here manually.
2462 // FIXME: somehow make the template accessible here.
2463 if (data->optionals() > 0)
2464 features.require("xargs");
2470 Buffer::References & Buffer::references(docstring const & label)
2473 return const_cast<Buffer *>(masterBuffer())->references(label);
2475 RefCache::iterator it = d->ref_cache_.find(label);
2476 if (it != d->ref_cache_.end())
2477 return it->second.second;
2479 static InsetLabel const * dummy_il = 0;
2480 static References const dummy_refs;
2481 it = d->ref_cache_.insert(
2482 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2483 return it->second.second;
2487 Buffer::References const & Buffer::references(docstring const & label) const
2489 return const_cast<Buffer *>(this)->references(label);
2493 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2495 masterBuffer()->d->ref_cache_[label].first = il;
2499 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2501 return masterBuffer()->d->ref_cache_[label].first;
2505 void Buffer::clearReferenceCache() const
2508 d->ref_cache_.clear();
2512 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2515 //FIXME: This does not work for child documents yet.
2516 LASSERT(code == CITE_CODE, /**/);
2517 // Check if the label 'from' appears more than once
2518 vector<docstring> labels;
2520 BiblioInfo const & keys = masterBibInfo();
2521 BiblioInfo::const_iterator bit = keys.begin();
2522 BiblioInfo::const_iterator bend = keys.end();
2524 for (; bit != bend; ++bit)
2526 labels.push_back(bit->first);
2529 if (count(labels.begin(), labels.end(), from) > 1)
2532 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2533 if (it->lyxCode() == code) {
2534 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2535 docstring const oldValue = inset.getParam(paramName);
2536 if (oldValue == from)
2537 inset.setParam(paramName, to);
2543 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2544 pit_type par_end, bool full_source) const
2546 OutputParams runparams(¶ms().encoding());
2547 runparams.nice = true;
2548 runparams.flavor = params().useXetex ?
2549 OutputParams::XETEX : OutputParams::LATEX;
2550 runparams.linelen = lyxrc.plaintext_linelen;
2551 // No side effect of file copying and image conversion
2552 runparams.dryrun = true;
2555 os << "% " << _("Preview source code") << "\n\n";
2557 d->texrow.newline();
2558 d->texrow.newline();
2560 writeDocBookSource(os, absFileName(), runparams, false);
2562 // latex or literate
2563 writeLaTeXSource(os, string(), runparams, true, true);
2565 runparams.par_begin = par_begin;
2566 runparams.par_end = par_end;
2567 if (par_begin + 1 == par_end) {
2569 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2573 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2574 convert<docstring>(par_begin),
2575 convert<docstring>(par_end - 1))
2582 // output paragraphs
2584 docbookParagraphs(paragraphs(), *this, os, runparams);
2586 // latex or literate
2587 latexParagraphs(*this, text(), os, texrow, runparams);
2592 ErrorList & Buffer::errorList(string const & type) const
2594 static ErrorList emptyErrorList;
2595 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2596 if (I == d->errorLists.end())
2597 return emptyErrorList;
2603 void Buffer::updateTocItem(std::string const & type,
2604 DocIterator const & dit) const
2607 gui_->updateTocItem(type, dit);
2611 void Buffer::structureChanged() const
2614 gui_->structureChanged();
2618 void Buffer::errors(string const & err, bool from_master) const
2621 gui_->errors(err, from_master);
2625 void Buffer::message(docstring const & msg) const
2632 void Buffer::setBusy(bool on) const
2639 void Buffer::setReadOnly(bool on) const
2642 d->wa_->setReadOnly(on);
2646 void Buffer::updateTitles() const
2649 d->wa_->updateTitles();
2653 void Buffer::resetAutosaveTimers() const
2656 gui_->resetAutosaveTimers();
2660 bool Buffer::hasGuiDelegate() const
2666 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2675 class AutoSaveBuffer : public ForkedProcess {
2678 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2679 : buffer_(buffer), fname_(fname) {}
2681 virtual boost::shared_ptr<ForkedProcess> clone() const
2683 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2688 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2689 from_utf8(fname_.absFilename())));
2690 return run(DontWait);
2694 virtual int generateChild();
2696 Buffer const & buffer_;
2701 int AutoSaveBuffer::generateChild()
2703 // tmp_ret will be located (usually) in /tmp
2704 // will that be a problem?
2705 // Note that this calls ForkedCalls::fork(), so it's
2706 // ok cross-platform.
2707 pid_t const pid = fork();
2708 // If you want to debug the autosave
2709 // you should set pid to -1, and comment out the fork.
2710 if (pid != 0 && pid != -1)
2713 // pid = -1 signifies that lyx was unable
2714 // to fork. But we will do the save
2716 bool failed = false;
2717 FileName const tmp_ret = FileName::tempName("lyxauto");
2718 if (!tmp_ret.empty()) {
2719 buffer_.writeFile(tmp_ret);
2720 // assume successful write of tmp_ret
2721 if (!tmp_ret.moveTo(fname_))
2727 // failed to write/rename tmp_ret so try writing direct
2728 if (!buffer_.writeFile(fname_)) {
2729 // It is dangerous to do this in the child,
2730 // but safe in the parent, so...
2731 if (pid == -1) // emit message signal.
2732 buffer_.message(_("Autosave failed!"));
2736 if (pid == 0) // we are the child so...
2745 FileName Buffer::getAutosaveFilename() const
2747 // if the document is unnamed try to save in the backup dir, else
2748 // in the default document path, and as a last try in the filePath,
2749 // which will most often be the temporary directory
2752 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
2753 : lyxrc.backupdir_path;
2754 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
2757 string const fname = "#" + d->filename.onlyFileName() + "#";
2758 return makeAbsPath(fname, fpath);
2762 void Buffer::removeAutosaveFile() const
2764 FileName const f = getAutosaveFilename();
2770 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
2772 FileName const newauto = getAutosaveFilename();
2773 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
2774 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
2778 // Perfect target for a thread...
2779 void Buffer::autoSave() const
2781 if (isBakClean() || isReadonly()) {
2782 // We don't save now, but we'll try again later
2783 resetAutosaveTimers();
2787 // emit message signal.
2788 message(_("Autosaving current document..."));
2789 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2793 resetAutosaveTimers();
2797 string Buffer::bufferFormat() const
2799 string format = params().documentClass().outputFormat();
2800 if (format == "latex") {
2801 if (params().useXetex)
2803 if (params().encoding().package() == Encoding::japanese)
2810 string Buffer::getDefaultOutputFormat() const
2812 if (!params().defaultOutputFormat.empty()
2813 && params().defaultOutputFormat != "default")
2814 return params().defaultOutputFormat;
2815 typedef vector<Format const *> Formats;
2816 Formats formats = exportableFormats(true);
2819 || params().useXetex
2820 || params().encoding().package() == Encoding::japanese) {
2821 if (formats.empty())
2823 // return the first we find
2824 return formats.front()->name();
2826 return lyxrc.default_view_format;
2831 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2832 string & result_file) const
2834 string backend_format;
2835 OutputParams runparams(¶ms().encoding());
2836 runparams.flavor = OutputParams::LATEX;
2837 runparams.linelen = lyxrc.plaintext_linelen;
2838 vector<string> backs = backends();
2839 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2840 // Get shortest path to format
2841 Graph::EdgePath path;
2842 for (vector<string>::const_iterator it = backs.begin();
2843 it != backs.end(); ++it) {
2844 Graph::EdgePath p = theConverters().getPath(*it, format);
2845 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2846 backend_format = *it;
2851 runparams.flavor = theConverters().getFlavor(path);
2853 Alert::error(_("Couldn't export file"),
2854 bformat(_("No information for exporting the format %1$s."),
2855 formats.prettyName(format)));
2859 backend_format = format;
2860 // FIXME: Don't hardcode format names here, but use a flag
2861 if (backend_format == "pdflatex")
2862 runparams.flavor = OutputParams::PDFLATEX;
2865 string filename = latexName(false);
2866 filename = addName(temppath(), filename);
2867 filename = changeExtension(filename,
2868 formats.extension(backend_format));
2871 updateMacroInstances();
2873 // Plain text backend
2874 if (backend_format == "text")
2875 writePlaintextFile(*this, FileName(filename), runparams);
2877 else if (backend_format == "xhtml")
2878 makeLyXHTMLFile(FileName(filename), runparams);
2879 else if (backend_format == "lyx")
2880 writeFile(FileName(filename));
2882 else if (isDocBook()) {
2883 runparams.nice = !put_in_tempdir;
2884 makeDocBookFile(FileName(filename), runparams);
2887 else if (backend_format == format) {
2888 runparams.nice = true;
2889 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2891 } else if (!lyxrc.tex_allows_spaces
2892 && contains(filePath(), ' ')) {
2893 Alert::error(_("File name error"),
2894 _("The directory path to the document cannot contain spaces."));
2897 runparams.nice = false;
2898 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2902 string const error_type = (format == "program")
2903 ? "Build" : bufferFormat();
2904 ErrorList & error_list = d->errorLists[error_type];
2905 string const ext = formats.extension(format);
2906 FileName const tmp_result_file(changeExtension(filename, ext));
2907 bool const success = theConverters().convert(this, FileName(filename),
2908 tmp_result_file, FileName(absFileName()), backend_format, format,
2910 // Emit the signal to show the error list.
2911 if (format != backend_format) {
2913 // also to the children, in case of master-buffer-view
2914 std::vector<Buffer *> clist = getChildren();
2915 for (vector<Buffer *>::const_iterator cit = clist.begin();
2916 cit != clist.end(); ++cit)
2917 (*cit)->errors(error_type, true);
2922 if (put_in_tempdir) {
2923 result_file = tmp_result_file.absFilename();
2927 result_file = changeExtension(exportFileName().absFilename(), ext);
2928 // We need to copy referenced files (e. g. included graphics
2929 // if format == "dvi") to the result dir.
2930 vector<ExportedFile> const files =
2931 runparams.exportdata->externalFiles(format);
2932 string const dest = onlyPath(result_file);
2933 CopyStatus status = SUCCESS;
2934 for (vector<ExportedFile>::const_iterator it = files.begin();
2935 it != files.end() && status != CANCEL; ++it) {
2936 string const fmt = formats.getFormatFromFile(it->sourceName);
2937 status = copyFile(fmt, it->sourceName,
2938 makeAbsPath(it->exportName, dest),
2939 it->exportName, status == FORCE);
2941 if (status == CANCEL) {
2942 message(_("Document export cancelled."));
2943 } else if (tmp_result_file.exists()) {
2944 // Finally copy the main file
2945 status = copyFile(format, tmp_result_file,
2946 FileName(result_file), result_file,
2948 message(bformat(_("Document exported as %1$s "
2950 formats.prettyName(format),
2951 makeDisplayPath(result_file)));
2953 // This must be a dummy converter like fax (bug 1888)
2954 message(bformat(_("Document exported as %1$s"),
2955 formats.prettyName(format)));
2962 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2965 return doExport(format, put_in_tempdir, result_file);
2969 bool Buffer::preview(string const & format) const
2972 if (!doExport(format, true, result_file))
2974 return formats.view(*this, FileName(result_file), format);
2978 bool Buffer::isExportable(string const & format) const
2980 vector<string> backs = backends();
2981 for (vector<string>::const_iterator it = backs.begin();
2982 it != backs.end(); ++it)
2983 if (theConverters().isReachable(*it, format))
2989 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2991 vector<string> backs = backends();
2992 vector<Format const *> result =
2993 theConverters().getReachable(backs[0], only_viewable, true);
2994 for (vector<string>::const_iterator it = backs.begin() + 1;
2995 it != backs.end(); ++it) {
2996 vector<Format const *> r =
2997 theConverters().getReachable(*it, only_viewable, false);
2998 result.insert(result.end(), r.begin(), r.end());
3004 vector<string> Buffer::backends() const
3007 if (params().baseClass()->isTeXClassAvailable()) {
3008 v.push_back(bufferFormat());
3009 // FIXME: Don't hardcode format names here, but use a flag
3010 if (v.back() == "latex")
3011 v.push_back("pdflatex");
3013 v.push_back("text");
3014 v.push_back("xhtml");
3020 bool Buffer::readFileHelper(FileName const & s)
3022 // File information about normal file
3024 docstring const file = makeDisplayPath(s.absFilename(), 50);
3025 docstring text = bformat(_("The specified document\n%1$s"
3026 "\ncould not be read."), file);
3027 Alert::error(_("Could not read document"), text);
3031 // Check if emergency save file exists and is newer.
3032 FileName const e(s.absFilename() + ".emergency");
3034 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3035 docstring const file = makeDisplayPath(s.absFilename(), 20);
3036 docstring const text =
3037 bformat(_("An emergency save of the document "
3039 "Recover emergency save?"), file);
3040 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3041 _("&Recover"), _("&Load Original"),
3045 // the file is not saved if we load the emergency file.
3055 // Now check if autosave file is newer.
3056 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3058 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3059 docstring const file = makeDisplayPath(s.absFilename(), 20);
3060 docstring const text =
3061 bformat(_("The backup of the document "
3062 "%1$s is newer.\n\nLoad the "
3063 "backup instead?"), file);
3064 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3065 _("&Load backup"), _("Load &original"),
3069 // the file is not saved if we load the autosave file.
3073 // Here we delete the autosave
3084 bool Buffer::loadLyXFile(FileName const & s)
3086 if (s.isReadableFile()) {
3087 if (readFileHelper(s)) {
3088 lyxvc().file_found_hook(s);
3089 if (!s.isWritable())
3094 docstring const file = makeDisplayPath(s.absFilename(), 20);
3095 // Here we probably should run
3096 if (LyXVC::file_not_found_hook(s)) {
3097 docstring const text =
3098 bformat(_("Do you want to retrieve the document"
3099 " %1$s from version control?"), file);
3100 int const ret = Alert::prompt(_("Retrieve from version control?"),
3101 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3104 // How can we know _how_ to do the checkout?
3105 // With the current VC support it has to be,
3106 // a RCS file since CVS do not have special ,v files.
3108 return loadLyXFile(s);
3116 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3118 TeXErrors::Errors::const_iterator cit = terr.begin();
3119 TeXErrors::Errors::const_iterator end = terr.end();
3121 for (; cit != end; ++cit) {
3124 int errorRow = cit->error_in_line;
3125 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3131 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3132 } while (found && id_start == id_end && pos_start == pos_end);
3134 errorList.push_back(ErrorItem(cit->error_desc,
3135 cit->error_text, id_start, pos_start, pos_end));
3140 void Buffer::setBuffersForInsets() const
3142 inset().setBuffer(const_cast<Buffer &>(*this));
3146 void Buffer::updateLabels(UpdateScope scope) const
3148 // Use the master text class also for child documents
3149 Buffer const * const master = masterBuffer();
3150 DocumentClass const & textclass = master->params().documentClass();
3152 // keep the buffers to be children in this set. If the call from the
3153 // master comes back we can see which of them were actually seen (i.e.
3154 // via an InsetInclude). The remaining ones in the set need still be updated.
3155 static std::set<Buffer const *> bufToUpdate;
3156 if (scope == UpdateMaster) {
3157 // If this is a child document start with the master
3158 if (master != this) {
3159 bufToUpdate.insert(this);
3160 master->updateLabels();
3161 // Do this here in case the master has no gui associated with it. Then,
3162 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3166 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3167 if (bufToUpdate.find(this) == bufToUpdate.end())
3171 // start over the counters in the master
3172 textclass.counters().reset();
3175 // update will be done below for this buffer
3176 bufToUpdate.erase(this);
3178 // update all caches
3179 clearReferenceCache();
3182 Buffer & cbuf = const_cast<Buffer &>(*this);
3184 LASSERT(!text().paragraphs().empty(), /**/);
3187 ParIterator parit = cbuf.par_iterator_begin();
3188 updateLabels(parit);
3191 // TocBackend update will be done later.
3194 cbuf.tocBackend().update();
3195 if (scope == UpdateMaster)
3196 cbuf.structureChanged();
3200 static depth_type getDepth(DocIterator const & it)
3202 depth_type depth = 0;
3203 for (size_t i = 0 ; i < it.depth() ; ++i)
3204 if (!it[i].inset().inMathed())
3205 depth += it[i].paragraph().getDepth() + 1;
3206 // remove 1 since the outer inset does not count
3210 static depth_type getItemDepth(ParIterator const & it)
3212 Paragraph const & par = *it;
3213 LabelType const labeltype = par.layout().labeltype;
3215 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3218 // this will hold the lowest depth encountered up to now.
3219 depth_type min_depth = getDepth(it);
3220 ParIterator prev_it = it;
3223 --prev_it.top().pit();
3225 // start of nested inset: go to outer par
3227 if (prev_it.empty()) {
3228 // start of document: nothing to do
3233 // We search for the first paragraph with same label
3234 // that is not more deeply nested.
3235 Paragraph & prev_par = *prev_it;
3236 depth_type const prev_depth = getDepth(prev_it);
3237 if (labeltype == prev_par.layout().labeltype) {
3238 if (prev_depth < min_depth)
3239 return prev_par.itemdepth + 1;
3240 if (prev_depth == min_depth)
3241 return prev_par.itemdepth;
3243 min_depth = min(min_depth, prev_depth);
3244 // small optimization: if we are at depth 0, we won't
3245 // find anything else
3246 if (prev_depth == 0)
3252 static bool needEnumCounterReset(ParIterator const & it)
3254 Paragraph const & par = *it;
3255 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3256 depth_type const cur_depth = par.getDepth();
3257 ParIterator prev_it = it;
3258 while (prev_it.pit()) {
3259 --prev_it.top().pit();
3260 Paragraph const & prev_par = *prev_it;
3261 if (prev_par.getDepth() <= cur_depth)
3262 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3264 // start of nested inset: reset
3269 // set the label of a paragraph. This includes the counters.
3270 static void setLabel(Buffer const & buf, ParIterator & it)
3272 BufferParams const & bp = buf.masterBuffer()->params();
3273 DocumentClass const & textclass = bp.documentClass();
3274 Paragraph & par = it.paragraph();
3275 Layout const & layout = par.layout();
3276 Counters & counters = textclass.counters();
3278 if (par.params().startOfAppendix()) {
3279 // FIXME: only the counter corresponding to toplevel
3280 // sectionning should be reset
3282 counters.appendix(true);
3284 par.params().appendix(counters.appendix());
3286 // Compute the item depth of the paragraph
3287 par.itemdepth = getItemDepth(it);
3289 if (layout.margintype == MARGIN_MANUAL
3290 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3291 if (par.params().labelWidthString().empty())
3292 par.params().labelWidthString(par.expandLabel(layout, bp));
3294 par.params().labelWidthString(docstring());
3297 switch(layout.labeltype) {
3299 if (layout.toclevel <= bp.secnumdepth
3300 && (layout.latextype != LATEX_ENVIRONMENT
3301 || isFirstInSequence(it.pit(), it.plist()))) {
3302 counters.step(layout.counter);
3303 par.params().labelString(
3304 par.expandLabel(layout, bp));
3306 par.params().labelString(docstring());
3309 case LABEL_ITEMIZE: {
3310 // At some point of time we should do something more
3311 // clever here, like:
3312 // par.params().labelString(
3313 // bp.user_defined_bullet(par.itemdepth).getText());
3314 // for now, use a simple hardcoded label
3315 docstring itemlabel;
3316 switch (par.itemdepth) {
3318 itemlabel = char_type(0x2022);
3321 itemlabel = char_type(0x2013);
3324 itemlabel = char_type(0x2217);
3327 itemlabel = char_type(0x2219); // or 0x00b7
3330 par.params().labelString(itemlabel);
3334 case LABEL_ENUMERATE: {
3335 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3337 switch (par.itemdepth) {
3346 enumcounter += "iv";
3349 // not a valid enumdepth...
3353 // Maybe we have to reset the enumeration counter.
3354 if (needEnumCounterReset(it))
3355 counters.reset(enumcounter);
3356 counters.step(enumcounter);
3358 string const & lang = par.getParLanguage(bp)->code();
3359 par.params().labelString(counters.theCounter(enumcounter, lang));
3364 case LABEL_SENSITIVE: {
3365 string const & type = counters.current_float();
3366 docstring full_label;
3368 full_label = buf.B_("Senseless!!! ");
3370 docstring name = buf.B_(textclass.floats().getType(type).name());
3371 if (counters.hasCounter(from_utf8(type))) {
3372 string const & lang = par.getParLanguage(bp)->code();
3373 counters.step(from_utf8(type));
3374 full_label = bformat(from_ascii("%1$s %2$s:"),
3376 counters.theCounter(from_utf8(type), lang));
3378 full_label = bformat(from_ascii("%1$s #:"), name);
3380 par.params().labelString(full_label);
3384 case LABEL_NO_LABEL:
3385 par.params().labelString(docstring());
3389 case LABEL_TOP_ENVIRONMENT:
3390 case LABEL_CENTERED_TOP_ENVIRONMENT:
3393 par.params().labelString(par.expandLabel(layout, bp));
3399 void Buffer::updateLabels(ParIterator & parit) const
3401 LASSERT(parit.pit() == 0, /**/);
3403 // set the position of the text in the buffer to be able
3404 // to resolve macros in it. This has nothing to do with
3405 // labels, but by putting it here we avoid implementing
3406 // a whole bunch of traversal routines just for this call.
3407 parit.text()->setMacrocontextPosition(parit);
3409 depth_type maxdepth = 0;
3410 pit_type const lastpit = parit.lastpit();
3411 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3412 // reduce depth if necessary
3413 parit->params().depth(min(parit->params().depth(), maxdepth));
3414 maxdepth = parit->getMaxDepthAfter();
3416 // set the counter for this paragraph
3417 setLabel(*this, parit);
3420 InsetList::const_iterator iit = parit->insetList().begin();
3421 InsetList::const_iterator end = parit->insetList().end();
3422 for (; iit != end; ++iit) {
3423 parit.pos() = iit->pos;
3424 iit->inset->updateLabels(parit);
3430 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3431 WordLangTuple & word_lang, docstring_list & suggestions) const
3435 suggestions.clear();
3436 word_lang = WordLangTuple();
3437 // OK, we start from here.
3438 DocIterator const end = doc_iterator_end(this);
3439 for (; from != end; from.forwardPos()) {
3440 // We are only interested in text so remove the math CursorSlice.
3441 while (from.inMathed())
3442 from.forwardInset();
3444 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {