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 "DocIterator.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
55 #include "TexStream.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
60 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/lassert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
109 using namespace lyx::support;
113 namespace Alert = frontend::Alert;
114 namespace os = support::os;
118 int const LYX_FORMAT = 336;
120 typedef map<string, bool> DepClean;
121 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
128 Impl(Buffer & parent, FileName const & file, bool readonly);
141 mutable TexRow texrow;
142 Buffer const * parent_buffer;
144 /// need to regenerate .tex?
148 mutable bool lyx_clean;
150 /// is autosave needed?
151 mutable bool bak_clean;
153 /// is this a unnamed file (New...)?
159 /// name of the file the buffer is associated with.
162 /** Set to true only when the file is fully loaded.
163 * Used to prevent the premature generation of previews
164 * and by the citation inset.
166 bool file_fully_loaded;
169 mutable TocBackend toc_backend;
172 typedef pair<DocIterator, MacroData> ScopeMacro;
173 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
174 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
175 /// map from the macro name to the position map,
176 /// which maps the macro definition position to the scope and the MacroData.
177 NamePositionScopeMacroMap macros;
180 /// positions of child buffers in the buffer
181 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
182 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
183 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
184 /// position of children buffers in this buffer
185 BufferPositionMap children_positions;
186 /// map from children inclusion positions to their scope and their buffer
187 PositionScopeBufferMap position_to_children;
189 /// Container for all sort of Buffer dependant errors.
190 map<string, ErrorList> errorLists;
192 /// timestamp and checksum used to test if the file has been externally
193 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
195 unsigned long checksum_;
198 frontend::WorkAreaManager * wa_;
203 /// A cache for the bibfiles (including bibfiles of loaded child
204 /// documents), needed for appropriate update of natbib labels.
205 mutable support::FileNameList bibfilesCache_;
207 // FIXME The caching mechanism could be improved. At present, we have a
208 // cache for each Buffer, that caches all the bibliography info for that
209 // Buffer. A more efficient solution would be to have a global cache per
210 // file, and then to construct the Buffer's bibinfo from that.
211 /// A cache for bibliography info
212 mutable BiblioInfo bibinfo_;
213 /// Cache of timestamps of .bib files
214 map<FileName, time_t> bibfileStatus_;
216 mutable RefCache ref_cache_;
218 /// our Text that should be wrapped in an InsetText
223 /// Creates the per buffer temporary directory
224 static FileName createBufferTmpDir()
227 // We are in our own directory. Why bother to mangle name?
228 // In fact I wrote this code to circumvent a problematic behaviour
229 // (bug?) of EMX mkstemp().
230 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
231 convert<string>(count++));
233 if (!tmpfl.createDirectory(0777)) {
234 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
235 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
236 from_utf8(tmpfl.absFilename())));
242 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
243 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
244 read_only(readonly_), filename(file), file_fully_loaded(false),
245 toc_backend(&parent), macro_lock(false), timestamp_(0),
246 checksum_(0), wa_(0), undo_(parent)
248 temppath = createBufferTmpDir();
249 lyxvc.setBuffer(&parent);
251 wa_ = new frontend::WorkAreaManager;
255 Buffer::Buffer(string const & file, bool readonly)
256 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
258 LYXERR(Debug::INFO, "Buffer::Buffer()");
260 d->inset.setBuffer(*this);
261 d->inset.initParagraphs(*this);
262 d->inset.setAutoBreakRows(true);
263 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
269 LYXERR(Debug::INFO, "Buffer::~Buffer()");
270 // here the buffer should take care that it is
271 // saved properly, before it goes into the void.
273 // GuiView already destroyed
276 // clear references to children in macro tables
277 d->children_positions.clear();
278 d->position_to_children.clear();
280 if (!d->temppath.destroyDirectory()) {
281 Alert::warning(_("Could not remove temporary directory"),
282 bformat(_("Could not remove the temporary directory %1$s"),
283 from_utf8(d->temppath.absFilename())));
286 // Remove any previewed LaTeX snippets associated with this buffer.
287 graphics::Previews::get().removeLoader(*this);
293 void Buffer::changed() const
300 frontend::WorkAreaManager & Buffer::workAreaManager() const
302 LASSERT(d->wa_, /**/);
307 Text & Buffer::text() const
309 return const_cast<Text &>(d->inset.text_);
313 Inset & Buffer::inset() const
315 return const_cast<InsetText &>(d->inset);
319 BufferParams & Buffer::params()
325 BufferParams const & Buffer::params() const
331 ParagraphList & Buffer::paragraphs()
333 return text().paragraphs();
337 ParagraphList const & Buffer::paragraphs() const
339 return text().paragraphs();
343 LyXVC & Buffer::lyxvc()
349 LyXVC const & Buffer::lyxvc() const
355 string const Buffer::temppath() const
357 return d->temppath.absFilename();
361 TexRow const & Buffer::texrow() const
367 TocBackend & Buffer::tocBackend() const
369 return d->toc_backend;
373 Undo & Buffer::undo()
379 string Buffer::latexName(bool const no_path) const
381 FileName latex_name = makeLatexName(d->filename);
382 return no_path ? latex_name.onlyFileName()
383 : latex_name.absFilename();
387 string Buffer::logName(LogType * type) const
389 string const filename = latexName(false);
391 if (filename.empty()) {
397 string const path = temppath();
399 FileName const fname(addName(temppath(),
400 onlyFilename(changeExtension(filename,
402 FileName const bname(
403 addName(path, onlyFilename(
404 changeExtension(filename,
405 formats.extension("literate") + ".out"))));
407 // If no Latex log or Build log is newer, show Build log
409 if (bname.exists() &&
410 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
411 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
414 return bname.absFilename();
416 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
419 return fname.absFilename();
423 void Buffer::setReadonly(bool const flag)
425 if (d->read_only != flag) {
432 void Buffer::setFileName(string const & newfile)
434 d->filename = makeAbsPath(newfile);
435 setReadonly(d->filename.isReadOnly());
440 int Buffer::readHeader(Lexer & lex)
442 int unknown_tokens = 0;
444 int begin_header_line = -1;
446 // Initialize parameters that may be/go lacking in header:
447 params().branchlist().clear();
448 params().preamble.erase();
449 params().options.erase();
450 params().master.erase();
451 params().float_placement.erase();
452 params().paperwidth.erase();
453 params().paperheight.erase();
454 params().leftmargin.erase();
455 params().rightmargin.erase();
456 params().topmargin.erase();
457 params().bottommargin.erase();
458 params().headheight.erase();
459 params().headsep.erase();
460 params().footskip.erase();
461 params().columnsep.erase();
462 params().fontsCJK.erase();
463 params().listings_params.clear();
464 params().clearLayoutModules();
465 params().pdfoptions().clear();
467 for (int i = 0; i < 4; ++i) {
468 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
469 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
472 ErrorList & errorList = d->errorLists["Parse"];
481 if (token == "\\end_header")
485 if (token == "\\begin_header") {
486 begin_header_line = line;
490 LYXERR(Debug::PARSER, "Handling document header token: `"
493 string unknown = params().readToken(lex, token, d->filename.onlyPath());
494 if (!unknown.empty()) {
495 if (unknown[0] != '\\' && token == "\\textclass") {
496 Alert::warning(_("Unknown document class"),
497 bformat(_("Using the default document class, because the "
498 "class %1$s is unknown."), from_utf8(unknown)));
501 docstring const s = bformat(_("Unknown token: "
505 errorList.push_back(ErrorItem(_("Document header error"),
510 if (begin_header_line) {
511 docstring const s = _("\\begin_header is missing");
512 errorList.push_back(ErrorItem(_("Document header error"),
516 params().makeDocumentClass();
518 return unknown_tokens;
523 // changed to be public and have one parameter
524 // Returns false if "\end_document" is not read (Asger)
525 bool Buffer::readDocument(Lexer & lex)
527 ErrorList & errorList = d->errorLists["Parse"];
530 if (!lex.checkFor("\\begin_document")) {
531 docstring const s = _("\\begin_document is missing");
532 errorList.push_back(ErrorItem(_("Document header error"),
536 // we are reading in a brand new document
537 LASSERT(paragraphs().empty(), /**/);
541 if (params().outputChanges) {
542 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
543 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
544 LaTeXFeatures::isAvailable("xcolor");
546 if (!dvipost && !xcolorsoul) {
547 Alert::warning(_("Changes not shown in LaTeX output"),
548 _("Changes will not be highlighted in LaTeX output, "
549 "because neither dvipost nor xcolor/soul are installed.\n"
550 "Please install these packages or redefine "
551 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
552 } else if (!xcolorsoul) {
553 Alert::warning(_("Changes not shown in LaTeX output"),
554 _("Changes will not be highlighted in LaTeX output "
555 "when using pdflatex, because xcolor and soul are not installed.\n"
556 "Please install both packages or redefine "
557 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
561 if (!params().master.empty()) {
562 FileName const master_file = makeAbsPath(params().master,
563 onlyPath(absFileName()));
564 if (isLyXFilename(master_file.absFilename())) {
565 Buffer * master = checkAndLoadLyXFile(master_file);
566 d->parent_buffer = master;
571 bool const res = text().read(*this, lex, errorList, &(d->inset));
574 updateMacroInstances();
579 // needed to insert the selection
580 void Buffer::insertStringAsLines(ParagraphList & pars,
581 pit_type & pit, pos_type & pos,
582 Font const & fn, docstring const & str, bool autobreakrows)
586 // insert the string, don't insert doublespace
587 bool space_inserted = true;
588 for (docstring::const_iterator cit = str.begin();
589 cit != str.end(); ++cit) {
590 Paragraph & par = pars[pit];
592 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
593 breakParagraph(params(), pars, pit, pos,
594 par.layout().isEnvironment());
597 space_inserted = true;
601 // do not insert consecutive spaces if !free_spacing
602 } else if ((*cit == ' ' || *cit == '\t') &&
603 space_inserted && !par.isFreeSpacing()) {
605 } else if (*cit == '\t') {
606 if (!par.isFreeSpacing()) {
607 // tabs are like spaces here
608 par.insertChar(pos, ' ', font, params().trackChanges);
610 space_inserted = true;
612 const pos_type n = 8 - pos % 8;
613 for (pos_type i = 0; i < n; ++i) {
614 par.insertChar(pos, ' ', font, params().trackChanges);
617 space_inserted = true;
619 } else if (!isPrintable(*cit)) {
620 // Ignore unprintables
623 // just insert the character
624 par.insertChar(pos, *cit, font, params().trackChanges);
626 space_inserted = (*cit == ' ');
633 bool Buffer::readString(string const & s)
635 params().compressed = false;
637 // remove dummy empty par
638 paragraphs().clear();
642 FileName const name = FileName::tempName();
643 switch (readFile(lex, name, true)) {
647 // We need to call lyx2lyx, so write the input to a file
648 ofstream os(name.toFilesystemEncoding().c_str());
651 return readFile(name);
661 bool Buffer::readFile(FileName const & filename)
663 FileName fname(filename);
665 // remove dummy empty par
666 paragraphs().clear();
669 if (readFile(lex, fname) != success)
676 bool Buffer::isFullyLoaded() const
678 return d->file_fully_loaded;
682 void Buffer::setFullyLoaded(bool value)
684 d->file_fully_loaded = value;
688 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
691 LASSERT(!filename.empty(), /**/);
693 // the first (non-comment) token _must_ be...
694 if (!lex.checkFor("\\lyxformat")) {
695 Alert::error(_("Document format failure"),
696 bformat(_("%1$s is not a readable LyX document."),
697 from_utf8(filename.absFilename())));
703 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
704 // if present remove ".," from string.
705 size_t dot = tmp_format.find_first_of(".,");
706 //lyxerr << " dot found at " << dot << endl;
707 if (dot != string::npos)
708 tmp_format.erase(dot, 1);
709 int const file_format = convert<int>(tmp_format);
710 //lyxerr << "format: " << file_format << endl;
712 // save timestamp and checksum of the original disk file, making sure
713 // to not overwrite them with those of the file created in the tempdir
714 // when it has to be converted to the current format.
716 // Save the timestamp and checksum of disk file. If filename is an
717 // emergency file, save the timestamp and checksum of the original lyx file
718 // because isExternallyModified will check for this file. (BUG4193)
719 string diskfile = filename.absFilename();
720 if (suffixIs(diskfile, ".emergency"))
721 diskfile = diskfile.substr(0, diskfile.size() - 10);
722 saveCheckSum(FileName(diskfile));
725 if (file_format != LYX_FORMAT) {
728 // lyx2lyx would fail
731 FileName const tmpfile = FileName::tempName();
732 if (tmpfile.empty()) {
733 Alert::error(_("Conversion failed"),
734 bformat(_("%1$s is from a different"
735 " version of LyX, but a temporary"
736 " file for converting it could"
738 from_utf8(filename.absFilename())));
741 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
742 if (lyx2lyx.empty()) {
743 Alert::error(_("Conversion script not found"),
744 bformat(_("%1$s is from a different"
745 " version of LyX, but the"
746 " conversion script lyx2lyx"
747 " could not be found."),
748 from_utf8(filename.absFilename())));
751 ostringstream command;
752 command << os::python()
753 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
754 << " -t " << convert<string>(LYX_FORMAT)
755 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
756 << ' ' << quoteName(filename.toFilesystemEncoding());
757 string const command_str = command.str();
759 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
761 cmd_ret const ret = runCommand(command_str);
762 if (ret.first != 0) {
763 Alert::error(_("Conversion script failed"),
764 bformat(_("%1$s is from a different version"
765 " of LyX, but the lyx2lyx script"
766 " failed to convert it."),
767 from_utf8(filename.absFilename())));
770 bool const ret = readFile(tmpfile);
771 // Do stuff with tmpfile name and buffer name here.
772 return ret ? success : failure;
777 if (readDocument(lex)) {
778 Alert::error(_("Document format failure"),
779 bformat(_("%1$s ended unexpectedly, which means"
780 " that it is probably corrupted."),
781 from_utf8(filename.absFilename())));
784 d->file_fully_loaded = true;
789 // Should probably be moved to somewhere else: BufferView? LyXView?
790 bool Buffer::save() const
792 // We don't need autosaves in the immediate future. (Asger)
793 resetAutosaveTimers();
795 string const encodedFilename = d->filename.toFilesystemEncoding();
798 bool madeBackup = false;
800 // make a backup if the file already exists
801 if (lyxrc.make_backup && fileName().exists()) {
802 backupName = FileName(absFileName() + '~');
803 if (!lyxrc.backupdir_path.empty()) {
804 string const mangledName =
805 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
806 backupName = FileName(addName(lyxrc.backupdir_path,
809 if (fileName().copyTo(backupName)) {
812 Alert::error(_("Backup failure"),
813 bformat(_("Cannot create backup file %1$s.\n"
814 "Please check whether the directory exists and is writeable."),
815 from_utf8(backupName.absFilename())));
816 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
820 // ask if the disk file has been externally modified (use checksum method)
821 if (fileName().exists() && isExternallyModified(checksum_method)) {
822 docstring const file = makeDisplayPath(absFileName(), 20);
823 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
824 "you want to overwrite this file?"), file);
825 int const ret = Alert::prompt(_("Overwrite modified file?"),
826 text, 1, 1, _("&Overwrite"), _("&Cancel"));
831 if (writeFile(d->filename)) {
835 // Saving failed, so backup is not backup
837 backupName.moveTo(d->filename);
843 bool Buffer::writeFile(FileName const & fname) const
845 if (d->read_only && fname == d->filename)
850 docstring const str = bformat(_("Saving document %1$s..."),
851 makeDisplayPath(fname.absFilename()));
854 if (params().compressed) {
855 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
856 retval = ofs && write(ofs);
858 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
859 retval = ofs && write(ofs);
863 message(str + _(" could not write file!"));
867 removeAutosaveFile(d->filename.absFilename());
869 saveCheckSum(d->filename);
870 message(str + _(" done."));
876 bool Buffer::write(ostream & ofs) const
879 // Use the standard "C" locale for file output.
880 ofs.imbue(locale::classic());
883 // The top of the file should not be written by params().
885 // write out a comment in the top of the file
886 ofs << "#LyX " << lyx_version
887 << " created this file. For more info see http://www.lyx.org/\n"
888 << "\\lyxformat " << LYX_FORMAT << "\n"
889 << "\\begin_document\n";
891 /// For each author, set 'used' to true if there is a change
892 /// by this author in the document; otherwise set it to 'false'.
893 AuthorList::Authors::const_iterator a_it = params().authors().begin();
894 AuthorList::Authors::const_iterator a_end = params().authors().end();
895 for (; a_it != a_end; ++a_it)
896 a_it->second.setUsed(false);
898 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
899 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
900 for ( ; it != end; ++it)
901 it->checkAuthors(params().authors());
903 // now write out the buffer parameters.
904 ofs << "\\begin_header\n";
905 params().writeFile(ofs);
906 ofs << "\\end_header\n";
909 ofs << "\n\\begin_body\n";
910 text().write(*this, ofs);
911 ofs << "\n\\end_body\n";
913 // Write marker that shows file is complete
914 ofs << "\\end_document" << endl;
916 // Shouldn't really be needed....
919 // how to check if close went ok?
920 // Following is an attempt... (BE 20001011)
922 // good() returns false if any error occured, including some
924 // bad() returns true if something bad happened in the buffer,
925 // which should include file system full errors.
930 lyxerr << "File was not closed properly." << endl;
937 bool Buffer::makeLaTeXFile(FileName const & fname,
938 string const & original_path,
939 OutputParams const & runparams,
940 bool output_preamble, bool output_body) const
942 string const encoding = runparams.encoding->iconvName();
943 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
946 try { ofs.reset(encoding); }
947 catch (iconv_codecvt_facet_exception & e) {
948 lyxerr << "Caught iconv exception: " << e.what() << endl;
949 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
950 "verify that the support software for your encoding (%1$s) is "
951 "properly installed"), from_ascii(encoding)));
954 if (!openFileWrite(ofs, fname))
957 //TexStream ts(ofs.rdbuf(), &texrow());
958 ErrorList & errorList = d->errorLists["Export"];
960 bool failed_export = false;
963 writeLaTeXSource(ofs, original_path,
964 runparams, output_preamble, output_body);
966 catch (EncodingException & e) {
967 odocstringstream ods;
968 ods.put(e.failed_char);
970 oss << "0x" << hex << e.failed_char << dec;
971 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
972 " (code point %2$s)"),
973 ods.str(), from_utf8(oss.str()));
974 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
975 "representable in the chosen encoding.\n"
976 "Changing the document encoding to utf8 could help."),
977 e.par_id, e.pos, e.pos + 1));
978 failed_export = true;
980 catch (iconv_codecvt_facet_exception & e) {
981 errorList.push_back(ErrorItem(_("iconv conversion failed"),
982 _(e.what()), -1, 0, 0));
983 failed_export = true;
985 catch (exception const & e) {
986 errorList.push_back(ErrorItem(_("conversion failed"),
987 _(e.what()), -1, 0, 0));
988 failed_export = true;
991 lyxerr << "Caught some really weird exception..." << endl;
997 failed_export = true;
998 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1002 return !failed_export;
1006 void Buffer::writeLaTeXSource(odocstream & os,
1007 string const & original_path,
1008 OutputParams const & runparams_in,
1009 bool const output_preamble, bool const output_body) const
1011 // The child documents, if any, shall be already loaded at this point.
1013 OutputParams runparams = runparams_in;
1015 // validate the buffer.
1016 LYXERR(Debug::LATEX, " Validating buffer...");
1017 LaTeXFeatures features(*this, params(), runparams);
1019 LYXERR(Debug::LATEX, " Buffer validation done.");
1021 // The starting paragraph of the coming rows is the
1022 // first paragraph of the document. (Asger)
1023 if (output_preamble && runparams.nice) {
1024 os << "%% LyX " << lyx_version << " created this file. "
1025 "For more info, see http://www.lyx.org/.\n"
1026 "%% Do not edit unless you really know what "
1028 d->texrow.newline();
1029 d->texrow.newline();
1031 LYXERR(Debug::INFO, "lyx document header finished");
1033 // Don't move this behind the parent_buffer=0 code below,
1034 // because then the macros will not get the right "redefinition"
1035 // flag as they don't see the parent macros which are output before.
1038 // fold macros if possible, still with parent buffer as the
1039 // macros will be put in the prefix anyway.
1040 updateMacroInstances();
1042 // There are a few differences between nice LaTeX and usual files:
1043 // usual is \batchmode and has a
1044 // special input@path to allow the including of figures
1045 // with either \input or \includegraphics (what figinsets do).
1046 // input@path is set when the actual parameter
1047 // original_path is set. This is done for usual tex-file, but not
1048 // for nice-latex-file. (Matthias 250696)
1049 // Note that input@path is only needed for something the user does
1050 // in the preamble, included .tex files or ERT, files included by
1051 // LyX work without it.
1052 if (output_preamble) {
1053 if (!runparams.nice) {
1054 // code for usual, NOT nice-latex-file
1055 os << "\\batchmode\n"; // changed
1056 // from \nonstopmode
1057 d->texrow.newline();
1059 if (!original_path.empty()) {
1061 // We don't know the encoding of inputpath
1062 docstring const inputpath = from_utf8(latex_path(original_path));
1063 os << "\\makeatletter\n"
1064 << "\\def\\input@path{{"
1065 << inputpath << "/}}\n"
1066 << "\\makeatother\n";
1067 d->texrow.newline();
1068 d->texrow.newline();
1069 d->texrow.newline();
1072 // get parent macros (if this buffer has a parent) which will be
1073 // written at the document begin further down.
1074 MacroSet parentMacros;
1075 listParentMacros(parentMacros, features);
1077 // Write the preamble
1078 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1084 os << "\\begin{document}\n";
1085 d->texrow.newline();
1087 // output the parent macros
1088 MacroSet::iterator it = parentMacros.begin();
1089 MacroSet::iterator end = parentMacros.end();
1090 for (; it != end; ++it)
1091 (*it)->write(os, true);
1092 } // output_preamble
1094 d->texrow.start(paragraphs().begin()->id(), 0);
1096 LYXERR(Debug::INFO, "preamble finished, now the body.");
1098 // if we are doing a real file with body, even if this is the
1099 // child of some other buffer, let's cut the link here.
1100 // This happens for example if only a child document is printed.
1101 Buffer const * save_parent = 0;
1102 if (output_preamble) {
1103 save_parent = d->parent_buffer;
1104 d->parent_buffer = 0;
1108 latexParagraphs(*this, text(), os, d->texrow, runparams);
1110 // Restore the parenthood if needed
1111 if (output_preamble)
1112 d->parent_buffer = save_parent;
1114 // add this just in case after all the paragraphs
1116 d->texrow.newline();
1118 if (output_preamble) {
1119 os << "\\end{document}\n";
1120 d->texrow.newline();
1121 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1123 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1125 runparams_in.encoding = runparams.encoding;
1127 // Just to be sure. (Asger)
1128 d->texrow.newline();
1130 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1131 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1135 bool Buffer::isLatex() const
1137 return params().documentClass().outputType() == LATEX;
1141 bool Buffer::isLiterate() const
1143 return params().documentClass().outputType() == LITERATE;
1147 bool Buffer::isDocBook() const
1149 return params().documentClass().outputType() == DOCBOOK;
1153 void Buffer::makeDocBookFile(FileName const & fname,
1154 OutputParams const & runparams,
1155 bool const body_only) const
1157 LYXERR(Debug::LATEX, "makeDocBookFile...");
1160 if (!openFileWrite(ofs, fname))
1163 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1167 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1171 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1172 OutputParams const & runparams,
1173 bool const only_body) const
1175 LaTeXFeatures features(*this, params(), runparams);
1180 DocumentClass const & tclass = params().documentClass();
1181 string const top_element = tclass.latexname();
1184 if (runparams.flavor == OutputParams::XML)
1185 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1188 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1191 if (! tclass.class_header().empty())
1192 os << from_ascii(tclass.class_header());
1193 else if (runparams.flavor == OutputParams::XML)
1194 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1195 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1197 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1199 docstring preamble = from_utf8(params().preamble);
1200 if (runparams.flavor != OutputParams::XML ) {
1201 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1202 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1203 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1204 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1207 string const name = runparams.nice
1208 ? changeExtension(absFileName(), ".sgml") : fname;
1209 preamble += features.getIncludedFiles(name);
1210 preamble += features.getLyXSGMLEntities();
1212 if (!preamble.empty()) {
1213 os << "\n [ " << preamble << " ]";
1218 string top = top_element;
1220 if (runparams.flavor == OutputParams::XML)
1221 top += params().language->code();
1223 top += params().language->code().substr(0,2);
1226 if (!params().options.empty()) {
1228 top += params().options;
1231 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1232 << " file was created by LyX " << lyx_version
1233 << "\n See http://www.lyx.org/ for more information -->\n";
1235 params().documentClass().counters().reset();
1239 sgml::openTag(os, top);
1241 docbookParagraphs(paragraphs(), *this, os, runparams);
1242 sgml::closeTag(os, top_element);
1246 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1247 // Other flags: -wall -v0 -x
1248 int Buffer::runChktex()
1252 // get LaTeX-Filename
1253 FileName const path(temppath());
1254 string const name = addName(path.absFilename(), latexName());
1255 string const org_path = filePath();
1257 PathChanger p(path); // path to LaTeX file
1258 message(_("Running chktex..."));
1260 // Generate the LaTeX file if neccessary
1261 OutputParams runparams(¶ms().encoding());
1262 runparams.flavor = OutputParams::LATEX;
1263 runparams.nice = false;
1264 makeLaTeXFile(FileName(name), org_path, runparams);
1267 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1268 int const res = chktex.run(terr); // run chktex
1271 Alert::error(_("chktex failure"),
1272 _("Could not run chktex successfully."));
1273 } else if (res > 0) {
1274 ErrorList & errlist = d->errorLists["ChkTeX"];
1276 bufferErrors(terr, errlist);
1287 void Buffer::validate(LaTeXFeatures & features) const
1289 params().validate(features);
1293 for_each(paragraphs().begin(), paragraphs().end(),
1294 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1296 if (lyxerr.debugging(Debug::LATEX)) {
1297 features.showStruct();
1302 void Buffer::getLabelList(vector<docstring> & list) const
1304 // If this is a child document, use the parent's list instead.
1305 if (d->parent_buffer) {
1306 d->parent_buffer->getLabelList(list);
1311 Toc & toc = d->toc_backend.toc("label");
1312 TocIterator toc_it = toc.begin();
1313 TocIterator end = toc.end();
1314 for (; toc_it != end; ++toc_it) {
1315 if (toc_it->depth() == 0)
1316 list.push_back(toc_it->str());
1321 void Buffer::updateBibfilesCache() const
1323 // If this is a child document, use the parent's cache instead.
1324 if (d->parent_buffer) {
1325 d->parent_buffer->updateBibfilesCache();
1329 d->bibfilesCache_.clear();
1330 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1331 if (it->lyxCode() == BIBTEX_CODE) {
1332 InsetBibtex const & inset =
1333 static_cast<InsetBibtex const &>(*it);
1334 support::FileNameList const bibfiles = inset.getBibFiles();
1335 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1338 } else if (it->lyxCode() == INCLUDE_CODE) {
1339 InsetInclude & inset =
1340 static_cast<InsetInclude &>(*it);
1341 inset.updateBibfilesCache();
1342 support::FileNameList const & bibfiles =
1343 inset.getBibfilesCache(*this);
1344 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1352 support::FileNameList const & Buffer::getBibfilesCache() const
1354 // If this is a child document, use the parent's cache instead.
1355 if (d->parent_buffer)
1356 return d->parent_buffer->getBibfilesCache();
1358 // We update the cache when first used instead of at loading time.
1359 if (d->bibfilesCache_.empty())
1360 const_cast<Buffer *>(this)->updateBibfilesCache();
1362 return d->bibfilesCache_;
1366 BiblioInfo const & Buffer::masterBibInfo() const
1368 // if this is a child document and the parent is already loaded
1369 // use the parent's list instead [ale990412]
1370 Buffer const * const tmp = masterBuffer();
1373 return tmp->masterBibInfo();
1374 return localBibInfo();
1378 BiblioInfo const & Buffer::localBibInfo() const
1380 support::FileNameList const & bibfilesCache = getBibfilesCache();
1381 // compare the cached timestamps with the actual ones.
1382 bool changed = false;
1383 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1384 support::FileNameList::const_iterator en = bibfilesCache.end();
1385 for (; ei != en; ++ ei) {
1386 time_t lastw = ei->lastModified();
1387 if (lastw != d->bibfileStatus_[*ei]) {
1389 d->bibfileStatus_[*ei] = lastw;
1395 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1396 it->fillWithBibKeys(d->bibinfo_, it);
1402 bool Buffer::isDepClean(string const & name) const
1404 DepClean::const_iterator const it = d->dep_clean.find(name);
1405 if (it == d->dep_clean.end())
1411 void Buffer::markDepClean(string const & name)
1413 d->dep_clean[name] = true;
1417 bool Buffer::dispatch(string const & command, bool * result)
1419 return dispatch(lyxaction.lookupFunc(command), result);
1423 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1425 bool dispatched = true;
1427 switch (func.action) {
1428 case LFUN_BUFFER_EXPORT: {
1429 bool const tmp = doExport(to_utf8(func.argument()), false);
1435 case LFUN_BRANCH_ACTIVATE:
1436 case LFUN_BRANCH_DEACTIVATE: {
1437 BranchList & branchList = params().branchlist();
1438 docstring const branchName = func.argument();
1439 Branch * branch = branchList.find(branchName);
1441 LYXERR0("Branch " << branchName << " does not exist.");
1443 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1455 void Buffer::changeLanguage(Language const * from, Language const * to)
1457 LASSERT(from, /**/);
1460 for_each(par_iterator_begin(),
1462 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1466 bool Buffer::isMultiLingual() const
1468 ParConstIterator end = par_iterator_end();
1469 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1470 if (it->isMultiLingual(params()))
1477 DocIterator Buffer::getParFromID(int const id) const
1480 // John says this is called with id == -1 from undo
1481 lyxerr << "getParFromID(), id: " << id << endl;
1482 return doc_iterator_end(inset());
1485 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1486 if (it.paragraph().id() == id)
1489 return doc_iterator_end(inset());
1493 bool Buffer::hasParWithID(int const id) const
1495 return !getParFromID(id).atEnd();
1499 ParIterator Buffer::par_iterator_begin()
1501 return ParIterator(doc_iterator_begin(inset()));
1505 ParIterator Buffer::par_iterator_end()
1507 return ParIterator(doc_iterator_end(inset()));
1511 ParConstIterator Buffer::par_iterator_begin() const
1513 return lyx::par_const_iterator_begin(inset());
1517 ParConstIterator Buffer::par_iterator_end() const
1519 return lyx::par_const_iterator_end(inset());
1523 Language const * Buffer::language() const
1525 return params().language;
1529 docstring const Buffer::B_(string const & l10n) const
1531 return params().B_(l10n);
1535 bool Buffer::isClean() const
1537 return d->lyx_clean;
1541 bool Buffer::isBakClean() const
1543 return d->bak_clean;
1547 bool Buffer::isExternallyModified(CheckMethod method) const
1549 LASSERT(d->filename.exists(), /**/);
1550 // if method == timestamp, check timestamp before checksum
1551 return (method == checksum_method
1552 || d->timestamp_ != d->filename.lastModified())
1553 && d->checksum_ != d->filename.checksum();
1557 void Buffer::saveCheckSum(FileName const & file) const
1559 if (file.exists()) {
1560 d->timestamp_ = file.lastModified();
1561 d->checksum_ = file.checksum();
1563 // in the case of save to a new file.
1570 void Buffer::markClean() const
1572 if (!d->lyx_clean) {
1573 d->lyx_clean = true;
1576 // if the .lyx file has been saved, we don't need an
1578 d->bak_clean = true;
1582 void Buffer::markBakClean() const
1584 d->bak_clean = true;
1588 void Buffer::setUnnamed(bool flag)
1594 bool Buffer::isUnnamed() const
1600 // FIXME: this function should be moved to buffer_pimpl.C
1601 void Buffer::markDirty()
1604 d->lyx_clean = false;
1607 d->bak_clean = false;
1609 DepClean::iterator it = d->dep_clean.begin();
1610 DepClean::const_iterator const end = d->dep_clean.end();
1612 for (; it != end; ++it)
1617 FileName Buffer::fileName() const
1623 string Buffer::absFileName() const
1625 return d->filename.absFilename();
1629 string Buffer::filePath() const
1631 return d->filename.onlyPath().absFilename() + "/";
1635 bool Buffer::isReadonly() const
1637 return d->read_only;
1641 void Buffer::setParent(Buffer const * buffer)
1643 // Avoids recursive include.
1644 d->parent_buffer = buffer == this ? 0 : buffer;
1649 Buffer const * Buffer::parent()
1651 return d->parent_buffer;
1655 Buffer const * Buffer::masterBuffer() const
1657 if (!d->parent_buffer)
1660 return d->parent_buffer->masterBuffer();
1664 template<typename M>
1665 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1670 typename M::iterator it = m.lower_bound(x);
1671 if (it == m.begin())
1679 MacroData const * Buffer::getBufferMacro(docstring const & name,
1680 DocIterator const & pos) const
1682 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1684 // if paragraphs have no macro context set, pos will be empty
1688 // we haven't found anything yet
1689 DocIterator bestPos = par_iterator_begin();
1690 MacroData const * bestData = 0;
1692 // find macro definitions for name
1693 Impl::NamePositionScopeMacroMap::iterator nameIt
1694 = d->macros.find(name);
1695 if (nameIt != d->macros.end()) {
1696 // find last definition in front of pos or at pos itself
1697 Impl::PositionScopeMacroMap::const_iterator it
1698 = greatest_below(nameIt->second, pos);
1699 if (it != nameIt->second.end()) {
1701 // scope ends behind pos?
1702 if (pos < it->second.first) {
1703 // Looks good, remember this. If there
1704 // is no external macro behind this,
1705 // we found the right one already.
1706 bestPos = it->first;
1707 bestData = &it->second.second;
1711 // try previous macro if there is one
1712 if (it == nameIt->second.begin())
1719 // find macros in included files
1720 Impl::PositionScopeBufferMap::const_iterator it
1721 = greatest_below(d->position_to_children, pos);
1722 if (it == d->position_to_children.end())
1723 // no children before
1727 // do we know something better (i.e. later) already?
1728 if (it->first < bestPos )
1731 // scope ends behind pos?
1732 if (pos < it->second.first) {
1733 // look for macro in external file
1734 d->macro_lock = true;
1735 MacroData const * data
1736 = it->second.second->getMacro(name, false);
1737 d->macro_lock = false;
1739 bestPos = it->first;
1745 // try previous file if there is one
1746 if (it == d->position_to_children.begin())
1751 // return the best macro we have found
1756 MacroData const * Buffer::getMacro(docstring const & name,
1757 DocIterator const & pos, bool global) const
1762 // query buffer macros
1763 MacroData const * data = getBufferMacro(name, pos);
1767 // If there is a master buffer, query that
1768 if (d->parent_buffer) {
1769 d->macro_lock = true;
1770 MacroData const * macro = d->parent_buffer->getMacro(
1771 name, *this, false);
1772 d->macro_lock = false;
1778 data = MacroTable::globalMacros().get(name);
1787 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1789 // set scope end behind the last paragraph
1790 DocIterator scope = par_iterator_begin();
1791 scope.pit() = scope.lastpit() + 1;
1793 return getMacro(name, scope, global);
1797 MacroData const * Buffer::getMacro(docstring const & name,
1798 Buffer const & child, bool global) const
1800 // look where the child buffer is included first
1801 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1802 if (it == d->children_positions.end())
1805 // check for macros at the inclusion position
1806 return getMacro(name, it->second, global);
1810 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1812 pit_type lastpit = it.lastpit();
1814 // look for macros in each paragraph
1815 while (it.pit() <= lastpit) {
1816 Paragraph & par = it.paragraph();
1818 // iterate over the insets of the current paragraph
1819 InsetList const & insets = par.insetList();
1820 InsetList::const_iterator iit = insets.begin();
1821 InsetList::const_iterator end = insets.end();
1822 for (; iit != end; ++iit) {
1823 it.pos() = iit->pos;
1825 // is it a nested text inset?
1826 if (iit->inset->asInsetText()) {
1827 // Inset needs its own scope?
1828 InsetText const * itext
1829 = iit->inset->asInsetText();
1830 bool newScope = itext->isMacroScope();
1832 // scope which ends just behind the inset
1833 DocIterator insetScope = it;
1836 // collect macros in inset
1837 it.push_back(CursorSlice(*iit->inset));
1838 updateMacros(it, newScope ? insetScope : scope);
1843 // is it an external file?
1844 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1845 // get buffer of external file
1846 InsetCommand const & inset
1847 = static_cast<InsetCommand const &>(*iit->inset);
1848 InsetCommandParams const & ip = inset.params();
1849 d->macro_lock = true;
1850 Buffer * child = loadIfNeeded(*this, ip);
1851 d->macro_lock = false;
1855 // register its position, but only when it is
1856 // included first in the buffer
1857 if (d->children_positions.find(child)
1858 == d->children_positions.end())
1859 d->children_positions[child] = it;
1861 // register child with its scope
1862 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1866 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1870 MathMacroTemplate & macroTemplate
1871 = static_cast<MathMacroTemplate &>(*iit->inset);
1872 MacroContext mc(*this, it);
1873 macroTemplate.updateToContext(mc);
1876 bool valid = macroTemplate.validMacro();
1877 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1878 // then the BufferView's cursor will be invalid in
1879 // some cases which leads to crashes.
1884 d->macros[macroTemplate.name()][it] =
1885 Impl::ScopeMacro(scope, MacroData(*this, it));
1895 void Buffer::updateMacros() const
1900 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1902 // start with empty table
1904 d->children_positions.clear();
1905 d->position_to_children.clear();
1907 // Iterate over buffer, starting with first paragraph
1908 // The scope must be bigger than any lookup DocIterator
1909 // later. For the global lookup, lastpit+1 is used, hence
1910 // we use lastpit+2 here.
1911 DocIterator it = par_iterator_begin();
1912 DocIterator outerScope = it;
1913 outerScope.pit() = outerScope.lastpit() + 2;
1914 updateMacros(it, outerScope);
1918 void Buffer::updateMacroInstances() const
1920 LYXERR(Debug::MACROS, "updateMacroInstances for "
1921 << d->filename.onlyFileName());
1922 DocIterator it = doc_iterator_begin(inset());
1923 DocIterator end = doc_iterator_end(inset());
1924 for (; it != end; it.forwardPos()) {
1925 // look for MathData cells in InsetMathNest insets
1926 Inset * inset = it.nextInset();
1930 InsetMath * minset = inset->asInsetMath();
1934 // update macro in all cells of the InsetMathNest
1935 DocIterator::idx_type n = minset->nargs();
1936 MacroContext mc = MacroContext(*this, it);
1937 for (DocIterator::idx_type i = 0; i < n; ++i) {
1938 MathData & data = minset->cell(i);
1939 data.updateMacros(0, mc);
1945 void Buffer::listMacroNames(MacroNameSet & macros) const
1950 d->macro_lock = true;
1952 // loop over macro names
1953 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1954 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1955 for (; nameIt != nameEnd; ++nameIt)
1956 macros.insert(nameIt->first);
1958 // loop over children
1959 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1960 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1961 for (; it != end; ++it)
1962 it->first->listMacroNames(macros);
1965 if (d->parent_buffer)
1966 d->parent_buffer->listMacroNames(macros);
1968 d->macro_lock = false;
1972 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1974 if (!d->parent_buffer)
1978 d->parent_buffer->listMacroNames(names);
1981 MacroNameSet::iterator it = names.begin();
1982 MacroNameSet::iterator end = names.end();
1983 for (; it != end; ++it) {
1985 MacroData const * data =
1986 d->parent_buffer->getMacro(*it, *this, false);
1988 macros.insert(data);
1990 // we cannot access the original MathMacroTemplate anymore
1991 // here to calls validate method. So we do its work here manually.
1992 // FIXME: somehow make the template accessible here.
1993 if (data->optionals() > 0)
1994 features.require("xargs");
2000 Buffer::References & Buffer::references(docstring const & label)
2002 if (d->parent_buffer)
2003 return const_cast<Buffer *>(masterBuffer())->references(label);
2005 RefCache::iterator it = d->ref_cache_.find(label);
2006 if (it != d->ref_cache_.end())
2007 return it->second.second;
2009 static InsetLabel const * dummy_il = 0;
2010 static References const dummy_refs;
2011 it = d->ref_cache_.insert(
2012 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2013 return it->second.second;
2017 Buffer::References const & Buffer::references(docstring const & label) const
2019 return const_cast<Buffer *>(this)->references(label);
2023 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2025 masterBuffer()->d->ref_cache_[label].first = il;
2029 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2031 return masterBuffer()->d->ref_cache_[label].first;
2035 void Buffer::clearReferenceCache() const
2037 if (!d->parent_buffer)
2038 d->ref_cache_.clear();
2042 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2045 //FIXME: This does not work for child documents yet.
2046 LASSERT(code == CITE_CODE, /**/);
2047 // Check if the label 'from' appears more than once
2048 vector<docstring> labels;
2050 BiblioInfo const & keys = masterBibInfo();
2051 BiblioInfo::const_iterator bit = keys.begin();
2052 BiblioInfo::const_iterator bend = keys.end();
2054 for (; bit != bend; ++bit)
2056 labels.push_back(bit->first);
2059 if (count(labels.begin(), labels.end(), from) > 1)
2062 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2063 if (it->lyxCode() == code) {
2064 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2065 docstring const oldValue = inset.getParam(paramName);
2066 if (oldValue == from)
2067 inset.setParam(paramName, to);
2073 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2074 pit_type par_end, bool full_source)
2076 OutputParams runparams(¶ms().encoding());
2077 runparams.nice = true;
2078 runparams.flavor = OutputParams::LATEX;
2079 runparams.linelen = lyxrc.plaintext_linelen;
2080 // No side effect of file copying and image conversion
2081 runparams.dryrun = true;
2085 os << "% " << _("Preview source code") << "\n\n";
2086 d->texrow.newline();
2087 d->texrow.newline();
2089 writeLaTeXSource(os, filePath(), runparams, true, true);
2091 writeDocBookSource(os, absFileName(), runparams, false);
2093 runparams.par_begin = par_begin;
2094 runparams.par_end = par_end;
2095 if (par_begin + 1 == par_end) {
2097 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2101 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2102 convert<docstring>(par_begin),
2103 convert<docstring>(par_end - 1))
2106 d->texrow.newline();
2107 d->texrow.newline();
2108 // output paragraphs
2110 latexParagraphs(*this, text(), os, d->texrow, runparams);
2113 docbookParagraphs(paragraphs(), *this, os, runparams);
2118 ErrorList & Buffer::errorList(string const & type) const
2120 static ErrorList emptyErrorList;
2121 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2122 if (I == d->errorLists.end())
2123 return emptyErrorList;
2129 void Buffer::structureChanged() const
2132 gui_->structureChanged();
2136 void Buffer::errors(string const & err) const
2143 void Buffer::message(docstring const & msg) const
2150 void Buffer::setBusy(bool on) const
2157 void Buffer::setReadOnly(bool on) const
2160 d->wa_->setReadOnly(on);
2164 void Buffer::updateTitles() const
2167 d->wa_->updateTitles();
2171 void Buffer::resetAutosaveTimers() const
2174 gui_->resetAutosaveTimers();
2178 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2187 class AutoSaveBuffer : public ForkedProcess {
2190 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2191 : buffer_(buffer), fname_(fname) {}
2193 virtual boost::shared_ptr<ForkedProcess> clone() const
2195 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2200 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2201 from_utf8(fname_.absFilename())));
2202 return run(DontWait);
2206 virtual int generateChild();
2208 Buffer const & buffer_;
2213 int AutoSaveBuffer::generateChild()
2215 // tmp_ret will be located (usually) in /tmp
2216 // will that be a problem?
2217 // Note that this calls ForkedCalls::fork(), so it's
2218 // ok cross-platform.
2219 pid_t const pid = fork();
2220 // If you want to debug the autosave
2221 // you should set pid to -1, and comment out the fork.
2222 if (pid != 0 && pid != -1)
2225 // pid = -1 signifies that lyx was unable
2226 // to fork. But we will do the save
2228 bool failed = false;
2229 FileName const tmp_ret = FileName::tempName("lyxauto");
2230 if (!tmp_ret.empty()) {
2231 buffer_.writeFile(tmp_ret);
2232 // assume successful write of tmp_ret
2233 if (!tmp_ret.moveTo(fname_))
2239 // failed to write/rename tmp_ret so try writing direct
2240 if (!buffer_.writeFile(fname_)) {
2241 // It is dangerous to do this in the child,
2242 // but safe in the parent, so...
2243 if (pid == -1) // emit message signal.
2244 buffer_.message(_("Autosave failed!"));
2248 if (pid == 0) // we are the child so...
2257 // Perfect target for a thread...
2258 void Buffer::autoSave() const
2260 if (isBakClean() || isReadonly()) {
2261 // We don't save now, but we'll try again later
2262 resetAutosaveTimers();
2266 // emit message signal.
2267 message(_("Autosaving current document..."));
2269 // create autosave filename
2270 string fname = filePath();
2272 fname += d->filename.onlyFileName();
2275 AutoSaveBuffer autosave(*this, FileName(fname));
2279 resetAutosaveTimers();
2283 string Buffer::bufferFormat() const
2293 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2294 string & result_file) const
2296 string backend_format;
2297 OutputParams runparams(¶ms().encoding());
2298 runparams.flavor = OutputParams::LATEX;
2299 runparams.linelen = lyxrc.plaintext_linelen;
2300 vector<string> backs = backends();
2301 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2302 // Get shortest path to format
2303 Graph::EdgePath path;
2304 for (vector<string>::const_iterator it = backs.begin();
2305 it != backs.end(); ++it) {
2306 Graph::EdgePath p = theConverters().getPath(*it, format);
2307 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2308 backend_format = *it;
2313 runparams.flavor = theConverters().getFlavor(path);
2315 Alert::error(_("Couldn't export file"),
2316 bformat(_("No information for exporting the format %1$s."),
2317 formats.prettyName(format)));
2321 backend_format = format;
2322 // FIXME: Don't hardcode format names here, but use a flag
2323 if (backend_format == "pdflatex")
2324 runparams.flavor = OutputParams::PDFLATEX;
2327 string filename = latexName(false);
2328 filename = addName(temppath(), filename);
2329 filename = changeExtension(filename,
2330 formats.extension(backend_format));
2333 updateMacroInstances();
2335 // Plain text backend
2336 if (backend_format == "text")
2337 writePlaintextFile(*this, FileName(filename), runparams);
2339 else if (backend_format == "lyx")
2340 writeFile(FileName(filename));
2342 else if (isDocBook()) {
2343 runparams.nice = !put_in_tempdir;
2344 makeDocBookFile(FileName(filename), runparams);
2347 else if (backend_format == format) {
2348 runparams.nice = true;
2349 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2351 } else if (!lyxrc.tex_allows_spaces
2352 && contains(filePath(), ' ')) {
2353 Alert::error(_("File name error"),
2354 _("The directory path to the document cannot contain spaces."));
2357 runparams.nice = false;
2358 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2362 string const error_type = (format == "program")
2363 ? "Build" : bufferFormat();
2364 string const ext = formats.extension(format);
2365 FileName const tmp_result_file(changeExtension(filename, ext));
2366 bool const success = theConverters().convert(this, FileName(filename),
2367 tmp_result_file, FileName(absFileName()), backend_format, format,
2368 errorList(error_type));
2369 // Emit the signal to show the error list.
2370 if (format != backend_format)
2375 if (put_in_tempdir) {
2376 result_file = tmp_result_file.absFilename();
2380 result_file = changeExtension(absFileName(), ext);
2381 // We need to copy referenced files (e. g. included graphics
2382 // if format == "dvi") to the result dir.
2383 vector<ExportedFile> const files =
2384 runparams.exportdata->externalFiles(format);
2385 string const dest = onlyPath(result_file);
2386 CopyStatus status = SUCCESS;
2387 for (vector<ExportedFile>::const_iterator it = files.begin();
2388 it != files.end() && status != CANCEL; ++it) {
2389 string const fmt = formats.getFormatFromFile(it->sourceName);
2390 status = copyFile(fmt, it->sourceName,
2391 makeAbsPath(it->exportName, dest),
2392 it->exportName, status == FORCE);
2394 if (status == CANCEL) {
2395 message(_("Document export cancelled."));
2396 } else if (tmp_result_file.exists()) {
2397 // Finally copy the main file
2398 status = copyFile(format, tmp_result_file,
2399 FileName(result_file), result_file,
2401 message(bformat(_("Document exported as %1$s "
2403 formats.prettyName(format),
2404 makeDisplayPath(result_file)));
2406 // This must be a dummy converter like fax (bug 1888)
2407 message(bformat(_("Document exported as %1$s"),
2408 formats.prettyName(format)));
2415 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2418 return doExport(format, put_in_tempdir, result_file);
2422 bool Buffer::preview(string const & format) const
2425 if (!doExport(format, true, result_file))
2427 return formats.view(*this, FileName(result_file), format);
2431 bool Buffer::isExportable(string const & format) const
2433 vector<string> backs = backends();
2434 for (vector<string>::const_iterator it = backs.begin();
2435 it != backs.end(); ++it)
2436 if (theConverters().isReachable(*it, format))
2442 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2444 vector<string> backs = backends();
2445 vector<Format const *> result =
2446 theConverters().getReachable(backs[0], only_viewable, true);
2447 for (vector<string>::const_iterator it = backs.begin() + 1;
2448 it != backs.end(); ++it) {
2449 vector<Format const *> r =
2450 theConverters().getReachable(*it, only_viewable, false);
2451 result.insert(result.end(), r.begin(), r.end());
2457 vector<string> Buffer::backends() const
2460 if (params().baseClass()->isTeXClassAvailable()) {
2461 v.push_back(bufferFormat());
2462 // FIXME: Don't hardcode format names here, but use a flag
2463 if (v.back() == "latex")
2464 v.push_back("pdflatex");
2466 v.push_back("text");
2472 bool Buffer::readFileHelper(FileName const & s)
2474 // File information about normal file
2476 docstring const file = makeDisplayPath(s.absFilename(), 50);
2477 docstring text = bformat(_("The specified document\n%1$s"
2478 "\ncould not be read."), file);
2479 Alert::error(_("Could not read document"), text);
2483 // Check if emergency save file exists and is newer.
2484 FileName const e(s.absFilename() + ".emergency");
2486 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2487 docstring const file = makeDisplayPath(s.absFilename(), 20);
2488 docstring const text =
2489 bformat(_("An emergency save of the document "
2491 "Recover emergency save?"), file);
2492 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2493 _("&Recover"), _("&Load Original"),
2497 // the file is not saved if we load the emergency file.
2507 // Now check if autosave file is newer.
2508 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2510 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2511 docstring const file = makeDisplayPath(s.absFilename(), 20);
2512 docstring const text =
2513 bformat(_("The backup of the document "
2514 "%1$s is newer.\n\nLoad the "
2515 "backup instead?"), file);
2516 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2517 _("&Load backup"), _("Load &original"),
2521 // the file is not saved if we load the autosave file.
2525 // Here we delete the autosave
2536 bool Buffer::loadLyXFile(FileName const & s)
2538 if (s.isReadableFile()) {
2539 if (readFileHelper(s)) {
2540 lyxvc().file_found_hook(s);
2541 if (!s.isWritable())
2546 docstring const file = makeDisplayPath(s.absFilename(), 20);
2547 // Here we probably should run
2548 if (LyXVC::file_not_found_hook(s)) {
2549 docstring const text =
2550 bformat(_("Do you want to retrieve the document"
2551 " %1$s from version control?"), file);
2552 int const ret = Alert::prompt(_("Retrieve from version control?"),
2553 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2556 // How can we know _how_ to do the checkout?
2557 // With the current VC support it has to be,
2558 // a RCS file since CVS do not have special ,v files.
2560 return loadLyXFile(s);
2568 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2570 TeXErrors::Errors::const_iterator cit = terr.begin();
2571 TeXErrors::Errors::const_iterator end = terr.end();
2573 for (; cit != end; ++cit) {
2576 int errorRow = cit->error_in_line;
2577 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2583 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2584 } while (found && id_start == id_end && pos_start == pos_end);
2586 errorList.push_back(ErrorItem(cit->error_desc,
2587 cit->error_text, id_start, pos_start, pos_end));