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/assert.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"
96 #include "support/FileZipListDir.h"
98 #include <boost/bind.hpp>
99 #include <boost/shared_ptr.hpp>
110 using namespace lyx::support;
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
119 int const LYX_FORMAT = 328;
121 typedef map<string, bool> DepClean;
122 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
129 Impl(Buffer & parent, FileName const & file, bool readonly);
142 mutable TexRow texrow;
143 Buffer const * parent_buffer;
145 /// need to regenerate .tex?
149 mutable bool lyx_clean;
151 /// is autosave needed?
152 mutable bool bak_clean;
154 /// is this a unnamed file (New...)?
160 /// name of the file the buffer is associated with.
163 /** Set to true only when the file is fully loaded.
164 * Used to prevent the premature generation of previews
165 * and by the citation inset.
167 bool file_fully_loaded;
170 mutable TocBackend toc_backend;
173 typedef pair<DocIterator, MacroData> ScopeMacro;
174 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
175 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
176 /// map from the macro name to the position map,
177 /// which maps the macro definition position to the scope and the MacroData.
178 NamePositionScopeMacroMap macros;
181 /// positions of child buffers in the buffer
182 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
183 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
184 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
185 /// position of children buffers in this buffer
186 BufferPositionMap children_positions;
187 /// map from children inclusion positions to their scope and their buffer
188 PositionScopeBufferMap position_to_children;
190 /// Container for all sort of Buffer dependant errors.
191 map<string, ErrorList> errorLists;
193 /// timestamp and checksum used to test if the file has been externally
194 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
196 unsigned long checksum_;
199 frontend::WorkAreaManager * wa_;
204 /// A cache for the bibfiles (including bibfiles of loaded child
205 /// documents), needed for appropriate update of natbib labels.
206 mutable support::FileNameList bibfilesCache_;
208 mutable RefCache ref_cache_;
210 /// our Text that should be wrapped in an InsetText
215 /// Creates the per buffer temporary directory
216 static FileName createBufferTmpDir()
219 // We are in our own directory. Why bother to mangle name?
220 // In fact I wrote this code to circumvent a problematic behaviour
221 // (bug?) of EMX mkstemp().
222 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
223 convert<string>(count++));
225 if (!tmpfl.createDirectory(0777)) {
226 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
227 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
228 from_utf8(tmpfl.absFilename())));
234 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
235 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
236 read_only(readonly_), filename(file), file_fully_loaded(false),
237 toc_backend(&parent), macro_lock(false),
238 timestamp_(0), checksum_(0), wa_(0), undo_(parent)
240 temppath = createBufferTmpDir();
241 lyxvc.setBuffer(&parent);
243 wa_ = new frontend::WorkAreaManager;
247 Buffer::Buffer(string const & file, bool readonly)
248 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
250 LYXERR(Debug::INFO, "Buffer::Buffer()");
252 d->inset.setBuffer(*this);
253 d->inset.initParagraphs(*this);
254 d->inset.setAutoBreakRows(true);
255 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
261 LYXERR(Debug::INFO, "Buffer::~Buffer()");
262 // here the buffer should take care that it is
263 // saved properly, before it goes into the void.
265 // GuiView already destroyed
268 // clear references to children in macro tables
269 d->children_positions.clear();
270 d->position_to_children.clear();
272 if (!d->temppath.destroyDirectory()) {
273 Alert::warning(_("Could not remove temporary directory"),
274 bformat(_("Could not remove the temporary directory %1$s"),
275 from_utf8(d->temppath.absFilename())));
278 // Remove any previewed LaTeX snippets associated with this buffer.
279 graphics::Previews::get().removeLoader(*this);
285 void Buffer::changed() const
292 frontend::WorkAreaManager & Buffer::workAreaManager() const
294 LASSERT(d->wa_, /**/);
299 Text & Buffer::text() const
301 return const_cast<Text &>(d->inset.text_);
305 Inset & Buffer::inset() const
307 return const_cast<InsetText &>(d->inset);
311 BufferParams & Buffer::params()
317 BufferParams const & Buffer::params() const
323 ParagraphList & Buffer::paragraphs()
325 return text().paragraphs();
329 ParagraphList const & Buffer::paragraphs() const
331 return text().paragraphs();
335 LyXVC & Buffer::lyxvc()
341 LyXVC const & Buffer::lyxvc() const
347 string const Buffer::temppath() const
349 return d->temppath.absFilename();
353 TexRow const & Buffer::texrow() const
359 TocBackend & Buffer::tocBackend() const
361 return d->toc_backend;
365 Undo & Buffer::undo()
371 string Buffer::latexName(bool const no_path) const
373 FileName latex_name = makeLatexName(d->filename);
374 return no_path ? latex_name.onlyFileName()
375 : latex_name.absFilename();
379 string Buffer::logName(LogType * type) const
381 string const filename = latexName(false);
383 if (filename.empty()) {
389 string const path = temppath();
391 FileName const fname(addName(temppath(),
392 onlyFilename(changeExtension(filename,
394 FileName const bname(
395 addName(path, onlyFilename(
396 changeExtension(filename,
397 formats.extension("literate") + ".out"))));
399 // If no Latex log or Build log is newer, show Build log
401 if (bname.exists() &&
402 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
403 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
406 return bname.absFilename();
408 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
411 return fname.absFilename();
415 void Buffer::setReadonly(bool const flag)
417 if (d->read_only != flag) {
424 void Buffer::setFileName(string const & newfile)
426 d->filename = makeAbsPath(newfile);
427 setReadonly(d->filename.isReadOnly());
432 int Buffer::readHeader(Lexer & lex)
434 int unknown_tokens = 0;
436 int begin_header_line = -1;
438 // Initialize parameters that may be/go lacking in header:
439 params().branchlist().clear();
440 params().preamble.erase();
441 params().options.erase();
442 params().float_placement.erase();
443 params().paperwidth.erase();
444 params().paperheight.erase();
445 params().leftmargin.erase();
446 params().rightmargin.erase();
447 params().topmargin.erase();
448 params().bottommargin.erase();
449 params().headheight.erase();
450 params().headsep.erase();
451 params().footskip.erase();
452 params().columnsep.erase();
453 params().listings_params.clear();
454 params().clearLayoutModules();
455 params().pdfoptions().clear();
457 for (int i = 0; i < 4; ++i) {
458 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
459 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
462 ErrorList & errorList = d->errorLists["Parse"];
471 if (token == "\\end_header")
475 if (token == "\\begin_header") {
476 begin_header_line = line;
480 LYXERR(Debug::PARSER, "Handling document header token: `"
483 string unknown = params().readToken(lex, token, d->filename.onlyPath());
484 if (!unknown.empty()) {
485 if (unknown[0] != '\\' && token == "\\textclass") {
486 Alert::warning(_("Unknown document class"),
487 bformat(_("Using the default document class, because the "
488 "class %1$s is unknown."), from_utf8(unknown)));
491 docstring const s = bformat(_("Unknown token: "
495 errorList.push_back(ErrorItem(_("Document header error"),
500 if (begin_header_line) {
501 docstring const s = _("\\begin_header is missing");
502 errorList.push_back(ErrorItem(_("Document header error"),
506 params().makeDocumentClass();
508 return unknown_tokens;
513 // changed to be public and have one parameter
514 // Returns false if "\end_document" is not read (Asger)
515 bool Buffer::readDocument(Lexer & lex)
517 ErrorList & errorList = d->errorLists["Parse"];
520 if (!lex.checkFor("\\begin_document")) {
521 docstring const s = _("\\begin_document is missing");
522 errorList.push_back(ErrorItem(_("Document header error"),
526 // we are reading in a brand new document
527 LASSERT(paragraphs().empty(), /**/);
531 if (params().outputChanges) {
532 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
533 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
534 LaTeXFeatures::isAvailable("xcolor");
536 if (!dvipost && !xcolorsoul) {
537 Alert::warning(_("Changes not shown in LaTeX output"),
538 _("Changes will not be highlighted in LaTeX output, "
539 "because neither dvipost nor xcolor/soul are installed.\n"
540 "Please install these packages or redefine "
541 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
542 } else if (!xcolorsoul) {
543 Alert::warning(_("Changes not shown in LaTeX output"),
544 _("Changes will not be highlighted in LaTeX output "
545 "when using pdflatex, because xcolor and soul are not installed.\n"
546 "Please install both packages or redefine "
547 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
552 bool const res = text().read(*this, lex, errorList, &(d->inset));
555 updateMacroInstances();
560 // needed to insert the selection
561 void Buffer::insertStringAsLines(ParagraphList & pars,
562 pit_type & pit, pos_type & pos,
563 Font const & fn, docstring const & str, bool autobreakrows)
567 // insert the string, don't insert doublespace
568 bool space_inserted = true;
569 for (docstring::const_iterator cit = str.begin();
570 cit != str.end(); ++cit) {
571 Paragraph & par = pars[pit];
573 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
574 breakParagraph(params(), pars, pit, pos,
575 par.layout().isEnvironment());
578 space_inserted = true;
582 // do not insert consecutive spaces if !free_spacing
583 } else if ((*cit == ' ' || *cit == '\t') &&
584 space_inserted && !par.isFreeSpacing()) {
586 } else if (*cit == '\t') {
587 if (!par.isFreeSpacing()) {
588 // tabs are like spaces here
589 par.insertChar(pos, ' ', font, params().trackChanges);
591 space_inserted = true;
593 const pos_type n = 8 - pos % 8;
594 for (pos_type i = 0; i < n; ++i) {
595 par.insertChar(pos, ' ', font, params().trackChanges);
598 space_inserted = true;
600 } else if (!isPrintable(*cit)) {
601 // Ignore unprintables
604 // just insert the character
605 par.insertChar(pos, *cit, font, params().trackChanges);
607 space_inserted = (*cit == ' ');
614 bool Buffer::readString(string const & s)
616 params().compressed = false;
618 // remove dummy empty par
619 paragraphs().clear();
623 FileName const name = FileName::tempName();
624 switch (readFile(lex, name, true)) {
628 // We need to call lyx2lyx, so write the input to a file
629 ofstream os(name.toFilesystemEncoding().c_str());
632 return readFile(name);
642 bool Buffer::readFile(FileName const & filename)
644 FileName fname(filename);
645 // Check if the file is compressed.
646 string format = filename.guessFormatFromContents();
647 if (format == "zip") {
648 // decompress to a temp directory
649 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
650 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
653 // remove dummy empty par
654 paragraphs().clear();
657 if (readFile(lex, fname) != success)
664 bool Buffer::isFullyLoaded() const
666 return d->file_fully_loaded;
670 void Buffer::setFullyLoaded(bool value)
672 d->file_fully_loaded = value;
676 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
679 LASSERT(!filename.empty(), /**/);
681 // the first (non-comment) token _must_ be...
682 if (!lex.checkFor("\\lyxformat")) {
683 Alert::error(_("Document format failure"),
684 bformat(_("%1$s is not a readable LyX document."),
685 from_utf8(filename.absFilename())));
691 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
692 // if present remove ".," from string.
693 size_t dot = tmp_format.find_first_of(".,");
694 //lyxerr << " dot found at " << dot << endl;
695 if (dot != string::npos)
696 tmp_format.erase(dot, 1);
697 int const file_format = convert<int>(tmp_format);
698 //lyxerr << "format: " << file_format << endl;
700 // save timestamp and checksum of the original disk file, making sure
701 // to not overwrite them with those of the file created in the tempdir
702 // when it has to be converted to the current format.
704 // Save the timestamp and checksum of disk file. If filename is an
705 // emergency file, save the timestamp and checksum of the original lyx file
706 // because isExternallyModified will check for this file. (BUG4193)
707 string diskfile = filename.absFilename();
708 if (suffixIs(diskfile, ".emergency"))
709 diskfile = diskfile.substr(0, diskfile.size() - 10);
710 saveCheckSum(FileName(diskfile));
713 if (file_format != LYX_FORMAT) {
716 // lyx2lyx would fail
719 FileName const tmpfile = FileName::tempName();
720 if (tmpfile.empty()) {
721 Alert::error(_("Conversion failed"),
722 bformat(_("%1$s is from a different"
723 " version of LyX, but a temporary"
724 " file for converting it could"
726 from_utf8(filename.absFilename())));
729 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
730 if (lyx2lyx.empty()) {
731 Alert::error(_("Conversion script not found"),
732 bformat(_("%1$s is from a different"
733 " version of LyX, but the"
734 " conversion script lyx2lyx"
735 " could not be found."),
736 from_utf8(filename.absFilename())));
739 ostringstream command;
740 command << os::python()
741 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
742 << " -t " << convert<string>(LYX_FORMAT)
743 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
744 << ' ' << quoteName(filename.toFilesystemEncoding());
745 string const command_str = command.str();
747 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
749 cmd_ret const ret = runCommand(command_str);
750 if (ret.first != 0) {
751 Alert::error(_("Conversion script failed"),
752 bformat(_("%1$s is from a different version"
753 " of LyX, but the lyx2lyx script"
754 " failed to convert it."),
755 from_utf8(filename.absFilename())));
758 bool const ret = readFile(tmpfile);
759 // Do stuff with tmpfile name and buffer name here.
760 return ret ? success : failure;
765 if (readDocument(lex)) {
766 Alert::error(_("Document format failure"),
767 bformat(_("%1$s ended unexpectedly, which means"
768 " that it is probably corrupted."),
769 from_utf8(filename.absFilename())));
772 d->file_fully_loaded = true;
777 // Should probably be moved to somewhere else: BufferView? LyXView?
778 bool Buffer::save() const
780 // We don't need autosaves in the immediate future. (Asger)
781 resetAutosaveTimers();
783 string const encodedFilename = d->filename.toFilesystemEncoding();
786 bool madeBackup = false;
788 // make a backup if the file already exists
789 if (lyxrc.make_backup && fileName().exists()) {
790 backupName = FileName(absFileName() + '~');
791 if (!lyxrc.backupdir_path.empty()) {
792 string const mangledName =
793 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
794 backupName = FileName(addName(lyxrc.backupdir_path,
797 if (fileName().copyTo(backupName)) {
800 Alert::error(_("Backup failure"),
801 bformat(_("Cannot create backup file %1$s.\n"
802 "Please check whether the directory exists and is writeable."),
803 from_utf8(backupName.absFilename())));
804 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
808 // ask if the disk file has been externally modified (use checksum method)
809 if (fileName().exists() && isExternallyModified(checksum_method)) {
810 docstring const file = makeDisplayPath(absFileName(), 20);
811 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
812 "you want to overwrite this file?"), file);
813 int const ret = Alert::prompt(_("Overwrite modified file?"),
814 text, 1, 1, _("&Overwrite"), _("&Cancel"));
819 if (writeFile(d->filename)) {
823 // Saving failed, so backup is not backup
825 backupName.moveTo(d->filename);
831 bool Buffer::writeFile(FileName const & fname) const
833 if (d->read_only && fname == d->filename)
838 docstring const str = bformat(_("Saving document %1$s..."),
839 makeDisplayPath(fname.absFilename()));
842 if (params().compressed) {
843 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
844 retval = ofs && write(ofs);
846 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
847 retval = ofs && write(ofs);
851 message(str + _(" could not write file!"));
855 removeAutosaveFile(d->filename.absFilename());
857 saveCheckSum(d->filename);
858 message(str + _(" done."));
864 bool Buffer::write(ostream & ofs) const
867 // Use the standard "C" locale for file output.
868 ofs.imbue(locale::classic());
871 // The top of the file should not be written by params().
873 // write out a comment in the top of the file
874 ofs << "#LyX " << lyx_version
875 << " created this file. For more info see http://www.lyx.org/\n"
876 << "\\lyxformat " << LYX_FORMAT << "\n"
877 << "\\begin_document\n";
879 /// For each author, set 'used' to true if there is a change
880 /// by this author in the document; otherwise set it to 'false'.
881 AuthorList::Authors::const_iterator a_it = params().authors().begin();
882 AuthorList::Authors::const_iterator a_end = params().authors().end();
883 for (; a_it != a_end; ++a_it)
884 a_it->second.setUsed(false);
886 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
887 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
888 for ( ; it != end; ++it)
889 it->checkAuthors(params().authors());
891 // now write out the buffer parameters.
892 ofs << "\\begin_header\n";
893 params().writeFile(ofs);
894 ofs << "\\end_header\n";
897 ofs << "\n\\begin_body\n";
898 text().write(*this, ofs);
899 ofs << "\n\\end_body\n";
901 // Write marker that shows file is complete
902 ofs << "\\end_document" << endl;
904 // Shouldn't really be needed....
907 // how to check if close went ok?
908 // Following is an attempt... (BE 20001011)
910 // good() returns false if any error occured, including some
912 // bad() returns true if something bad happened in the buffer,
913 // which should include file system full errors.
918 lyxerr << "File was not closed properly." << endl;
925 bool Buffer::makeLaTeXFile(FileName const & fname,
926 string const & original_path,
927 OutputParams const & runparams,
928 bool output_preamble, bool output_body) const
930 string const encoding = runparams.encoding->iconvName();
931 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
934 try { ofs.reset(encoding); }
935 catch (iconv_codecvt_facet_exception & e) {
936 lyxerr << "Caught iconv exception: " << e.what() << endl;
937 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
938 "verify that the support software for your encoding (%1$s) is "
939 "properly installed"), from_ascii(encoding)));
942 if (!openFileWrite(ofs, fname))
945 //TexStream ts(ofs.rdbuf(), &texrow());
946 ErrorList & errorList = d->errorLists["Export"];
948 bool failed_export = false;
951 writeLaTeXSource(ofs, original_path,
952 runparams, output_preamble, output_body);
954 catch (EncodingException & e) {
955 odocstringstream ods;
956 ods.put(e.failed_char);
958 oss << "0x" << hex << e.failed_char << dec;
959 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
960 " (code point %2$s)"),
961 ods.str(), from_utf8(oss.str()));
962 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
963 "representable in the chosen encoding.\n"
964 "Changing the document encoding to utf8 could help."),
965 e.par_id, e.pos, e.pos + 1));
966 failed_export = true;
968 catch (iconv_codecvt_facet_exception & e) {
969 errorList.push_back(ErrorItem(_("iconv conversion failed"),
970 _(e.what()), -1, 0, 0));
971 failed_export = true;
973 catch (exception const & e) {
974 errorList.push_back(ErrorItem(_("conversion failed"),
975 _(e.what()), -1, 0, 0));
976 failed_export = true;
979 lyxerr << "Caught some really weird exception..." << endl;
985 failed_export = true;
986 lyxerr << "File '" << fname << "' was not closed properly." << endl;
990 return !failed_export;
994 void Buffer::writeLaTeXSource(odocstream & os,
995 string const & original_path,
996 OutputParams const & runparams_in,
997 bool const output_preamble, bool const output_body) const
999 // The child documents, if any, shall be already loaded at this point.
1001 OutputParams runparams = runparams_in;
1003 // validate the buffer.
1004 LYXERR(Debug::LATEX, " Validating buffer...");
1005 LaTeXFeatures features(*this, params(), runparams);
1007 LYXERR(Debug::LATEX, " Buffer validation done.");
1009 // The starting paragraph of the coming rows is the
1010 // first paragraph of the document. (Asger)
1011 if (output_preamble && runparams.nice) {
1012 os << "%% LyX " << lyx_version << " created this file. "
1013 "For more info, see http://www.lyx.org/.\n"
1014 "%% Do not edit unless you really know what "
1016 d->texrow.newline();
1017 d->texrow.newline();
1019 LYXERR(Debug::INFO, "lyx document header finished");
1021 // Don't move this behind the parent_buffer=0 code below,
1022 // because then the macros will not get the right "redefinition"
1023 // flag as they don't see the parent macros which are output before.
1026 // fold macros if possible, still with parent buffer as the
1027 // macros will be put in the prefix anyway.
1028 updateMacroInstances();
1030 // There are a few differences between nice LaTeX and usual files:
1031 // usual is \batchmode and has a
1032 // special input@path to allow the including of figures
1033 // with either \input or \includegraphics (what figinsets do).
1034 // input@path is set when the actual parameter
1035 // original_path is set. This is done for usual tex-file, but not
1036 // for nice-latex-file. (Matthias 250696)
1037 // Note that input@path is only needed for something the user does
1038 // in the preamble, included .tex files or ERT, files included by
1039 // LyX work without it.
1040 if (output_preamble) {
1041 if (!runparams.nice) {
1042 // code for usual, NOT nice-latex-file
1043 os << "\\batchmode\n"; // changed
1044 // from \nonstopmode
1045 d->texrow.newline();
1047 if (!original_path.empty()) {
1049 // We don't know the encoding of inputpath
1050 docstring const inputpath = from_utf8(latex_path(original_path));
1051 os << "\\makeatletter\n"
1052 << "\\def\\input@path{{"
1053 << inputpath << "/}}\n"
1054 << "\\makeatother\n";
1055 d->texrow.newline();
1056 d->texrow.newline();
1057 d->texrow.newline();
1060 // get parent macros (if this buffer has a parent) which will be
1061 // written at the document begin further down.
1062 MacroSet parentMacros;
1063 listParentMacros(parentMacros, features);
1065 // Write the preamble
1066 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1072 os << "\\begin{document}\n";
1073 d->texrow.newline();
1075 // output the parent macros
1076 MacroSet::iterator it = parentMacros.begin();
1077 MacroSet::iterator end = parentMacros.end();
1078 for (; it != end; ++it)
1079 (*it)->write(os, true);
1080 } // output_preamble
1082 d->texrow.start(paragraphs().begin()->id(), 0);
1084 LYXERR(Debug::INFO, "preamble finished, now the body.");
1086 // if we are doing a real file with body, even if this is the
1087 // child of some other buffer, let's cut the link here.
1088 // This happens for example if only a child document is printed.
1089 Buffer const * save_parent = 0;
1090 if (output_preamble) {
1091 save_parent = d->parent_buffer;
1092 d->parent_buffer = 0;
1096 latexParagraphs(*this, text(), os, d->texrow, runparams);
1098 // Restore the parenthood if needed
1099 if (output_preamble)
1100 d->parent_buffer = save_parent;
1102 // add this just in case after all the paragraphs
1104 d->texrow.newline();
1106 if (output_preamble) {
1107 os << "\\end{document}\n";
1108 d->texrow.newline();
1109 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1111 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1113 runparams_in.encoding = runparams.encoding;
1115 // Just to be sure. (Asger)
1116 d->texrow.newline();
1118 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1119 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1123 bool Buffer::isLatex() const
1125 return params().documentClass().outputType() == LATEX;
1129 bool Buffer::isLiterate() const
1131 return params().documentClass().outputType() == LITERATE;
1135 bool Buffer::isDocBook() const
1137 return params().documentClass().outputType() == DOCBOOK;
1141 void Buffer::makeDocBookFile(FileName const & fname,
1142 OutputParams const & runparams,
1143 bool const body_only) const
1145 LYXERR(Debug::LATEX, "makeDocBookFile...");
1148 if (!openFileWrite(ofs, fname))
1151 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1155 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1159 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1160 OutputParams const & runparams,
1161 bool const only_body) const
1163 LaTeXFeatures features(*this, params(), runparams);
1168 DocumentClass const & tclass = params().documentClass();
1169 string const top_element = tclass.latexname();
1172 if (runparams.flavor == OutputParams::XML)
1173 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1176 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1179 if (! tclass.class_header().empty())
1180 os << from_ascii(tclass.class_header());
1181 else if (runparams.flavor == OutputParams::XML)
1182 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1183 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1185 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1187 docstring preamble = from_utf8(params().preamble);
1188 if (runparams.flavor != OutputParams::XML ) {
1189 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1190 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1191 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1192 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1195 string const name = runparams.nice
1196 ? changeExtension(absFileName(), ".sgml") : fname;
1197 preamble += features.getIncludedFiles(name);
1198 preamble += features.getLyXSGMLEntities();
1200 if (!preamble.empty()) {
1201 os << "\n [ " << preamble << " ]";
1206 string top = top_element;
1208 if (runparams.flavor == OutputParams::XML)
1209 top += params().language->code();
1211 top += params().language->code().substr(0,2);
1214 if (!params().options.empty()) {
1216 top += params().options;
1219 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1220 << " file was created by LyX " << lyx_version
1221 << "\n See http://www.lyx.org/ for more information -->\n";
1223 params().documentClass().counters().reset();
1227 sgml::openTag(os, top);
1229 docbookParagraphs(paragraphs(), *this, os, runparams);
1230 sgml::closeTag(os, top_element);
1234 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1235 // Other flags: -wall -v0 -x
1236 int Buffer::runChktex()
1240 // get LaTeX-Filename
1241 FileName const path(temppath());
1242 string const name = addName(path.absFilename(), latexName());
1243 string const org_path = filePath();
1245 PathChanger p(path); // path to LaTeX file
1246 message(_("Running chktex..."));
1248 // Generate the LaTeX file if neccessary
1249 OutputParams runparams(¶ms().encoding());
1250 runparams.flavor = OutputParams::LATEX;
1251 runparams.nice = false;
1252 makeLaTeXFile(FileName(name), org_path, runparams);
1255 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1256 int const res = chktex.run(terr); // run chktex
1259 Alert::error(_("chktex failure"),
1260 _("Could not run chktex successfully."));
1261 } else if (res > 0) {
1262 ErrorList & errlist = d->errorLists["ChkTeX"];
1264 bufferErrors(terr, errlist);
1275 void Buffer::validate(LaTeXFeatures & features) const
1277 params().validate(features);
1281 for_each(paragraphs().begin(), paragraphs().end(),
1282 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1284 if (lyxerr.debugging(Debug::LATEX)) {
1285 features.showStruct();
1290 void Buffer::getLabelList(vector<docstring> & list) const
1292 // If this is a child document, use the parent's list instead.
1293 if (d->parent_buffer) {
1294 d->parent_buffer->getLabelList(list);
1299 Toc & toc = d->toc_backend.toc("label");
1300 TocIterator toc_it = toc.begin();
1301 TocIterator end = toc.end();
1302 for (; toc_it != end; ++toc_it) {
1303 if (toc_it->depth() == 0)
1304 list.push_back(toc_it->str());
1309 void Buffer::updateBibfilesCache() const
1311 // If this is a child document, use the parent's cache instead.
1312 if (d->parent_buffer) {
1313 d->parent_buffer->updateBibfilesCache();
1317 d->bibfilesCache_.clear();
1318 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1319 if (it->lyxCode() == BIBTEX_CODE) {
1320 InsetBibtex const & inset =
1321 static_cast<InsetBibtex const &>(*it);
1322 support::FileNameList const bibfiles = inset.getBibFiles();
1323 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1326 } else if (it->lyxCode() == INCLUDE_CODE) {
1327 InsetInclude & inset =
1328 static_cast<InsetInclude &>(*it);
1329 inset.updateBibfilesCache();
1330 support::FileNameList const & bibfiles =
1331 inset.getBibfilesCache(*this);
1332 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1340 support::FileNameList const & Buffer::getBibfilesCache() const
1342 // If this is a child document, use the parent's cache instead.
1343 if (d->parent_buffer)
1344 return d->parent_buffer->getBibfilesCache();
1346 // We update the cache when first used instead of at loading time.
1347 if (d->bibfilesCache_.empty())
1348 const_cast<Buffer *>(this)->updateBibfilesCache();
1350 return d->bibfilesCache_;
1354 bool Buffer::isDepClean(string const & name) const
1356 DepClean::const_iterator const it = d->dep_clean.find(name);
1357 if (it == d->dep_clean.end())
1363 void Buffer::markDepClean(string const & name)
1365 d->dep_clean[name] = true;
1369 bool Buffer::dispatch(string const & command, bool * result)
1371 return dispatch(lyxaction.lookupFunc(command), result);
1375 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1377 bool dispatched = true;
1379 switch (func.action) {
1380 case LFUN_BUFFER_EXPORT: {
1381 bool const tmp = doExport(to_utf8(func.argument()), false);
1394 void Buffer::changeLanguage(Language const * from, Language const * to)
1396 LASSERT(from, /**/);
1399 for_each(par_iterator_begin(),
1401 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1405 bool Buffer::isMultiLingual() const
1407 ParConstIterator end = par_iterator_end();
1408 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1409 if (it->isMultiLingual(params()))
1416 DocIterator Buffer::getParFromID(int const id) const
1419 // John says this is called with id == -1 from undo
1420 lyxerr << "getParFromID(), id: " << id << endl;
1421 return doc_iterator_end(inset());
1424 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1425 if (it.paragraph().id() == id)
1428 return doc_iterator_end(inset());
1432 bool Buffer::hasParWithID(int const id) const
1434 return !getParFromID(id).atEnd();
1438 ParIterator Buffer::par_iterator_begin()
1440 return ParIterator(doc_iterator_begin(inset()));
1444 ParIterator Buffer::par_iterator_end()
1446 return ParIterator(doc_iterator_end(inset()));
1450 ParConstIterator Buffer::par_iterator_begin() const
1452 return lyx::par_const_iterator_begin(inset());
1456 ParConstIterator Buffer::par_iterator_end() const
1458 return lyx::par_const_iterator_end(inset());
1462 Language const * Buffer::language() const
1464 return params().language;
1468 docstring const Buffer::B_(string const & l10n) const
1470 return params().B_(l10n);
1474 bool Buffer::isClean() const
1476 return d->lyx_clean;
1480 bool Buffer::isBakClean() const
1482 return d->bak_clean;
1486 bool Buffer::isExternallyModified(CheckMethod method) const
1488 LASSERT(d->filename.exists(), /**/);
1489 // if method == timestamp, check timestamp before checksum
1490 return (method == checksum_method
1491 || d->timestamp_ != d->filename.lastModified())
1492 && d->checksum_ != d->filename.checksum();
1496 void Buffer::saveCheckSum(FileName const & file) const
1498 if (file.exists()) {
1499 d->timestamp_ = file.lastModified();
1500 d->checksum_ = file.checksum();
1502 // in the case of save to a new file.
1509 void Buffer::markClean() const
1511 if (!d->lyx_clean) {
1512 d->lyx_clean = true;
1515 // if the .lyx file has been saved, we don't need an
1517 d->bak_clean = true;
1521 void Buffer::markBakClean() const
1523 d->bak_clean = true;
1527 void Buffer::setUnnamed(bool flag)
1533 bool Buffer::isUnnamed() const
1539 // FIXME: this function should be moved to buffer_pimpl.C
1540 void Buffer::markDirty()
1543 d->lyx_clean = false;
1546 d->bak_clean = false;
1548 DepClean::iterator it = d->dep_clean.begin();
1549 DepClean::const_iterator const end = d->dep_clean.end();
1551 for (; it != end; ++it)
1556 FileName Buffer::fileName() const
1562 string Buffer::absFileName() const
1564 return d->filename.absFilename();
1568 string Buffer::filePath() const
1570 return d->filename.onlyPath().absFilename() + "/";
1574 bool Buffer::isReadonly() const
1576 return d->read_only;
1580 void Buffer::setParent(Buffer const * buffer)
1582 // Avoids recursive include.
1583 d->parent_buffer = buffer == this ? 0 : buffer;
1588 Buffer const * Buffer::parent()
1590 return d->parent_buffer;
1594 Buffer const * Buffer::masterBuffer() const
1596 if (!d->parent_buffer)
1599 return d->parent_buffer->masterBuffer();
1603 template<typename M>
1604 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1609 typename M::iterator it = m.lower_bound(x);
1610 if (it == m.begin())
1618 MacroData const * Buffer::getBufferMacro(docstring const & name,
1619 DocIterator const & pos) const
1621 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1623 // if paragraphs have no macro context set, pos will be empty
1627 // we haven't found anything yet
1628 DocIterator bestPos = par_iterator_begin();
1629 MacroData const * bestData = 0;
1631 // find macro definitions for name
1632 Impl::NamePositionScopeMacroMap::iterator nameIt
1633 = d->macros.find(name);
1634 if (nameIt != d->macros.end()) {
1635 // find last definition in front of pos or at pos itself
1636 Impl::PositionScopeMacroMap::const_iterator it
1637 = greatest_below(nameIt->second, pos);
1638 if (it != nameIt->second.end()) {
1640 // scope ends behind pos?
1641 if (pos < it->second.first) {
1642 // Looks good, remember this. If there
1643 // is no external macro behind this,
1644 // we found the right one already.
1645 bestPos = it->first;
1646 bestData = &it->second.second;
1650 // try previous macro if there is one
1651 if (it == nameIt->second.begin())
1658 // find macros in included files
1659 Impl::PositionScopeBufferMap::const_iterator it
1660 = greatest_below(d->position_to_children, pos);
1661 if (it == d->position_to_children.end())
1662 // no children before
1666 // do we know something better (i.e. later) already?
1667 if (it->first < bestPos )
1670 // scope ends behind pos?
1671 if (pos < it->second.first) {
1672 // look for macro in external file
1673 d->macro_lock = true;
1674 MacroData const * data
1675 = it->second.second->getMacro(name, false);
1676 d->macro_lock = false;
1678 bestPos = it->first;
1684 // try previous file if there is one
1685 if (it == d->position_to_children.begin())
1690 // return the best macro we have found
1695 MacroData const * Buffer::getMacro(docstring const & name,
1696 DocIterator const & pos, bool global) const
1701 // query buffer macros
1702 MacroData const * data = getBufferMacro(name, pos);
1706 // If there is a master buffer, query that
1707 if (d->parent_buffer) {
1708 d->macro_lock = true;
1709 MacroData const * macro = d->parent_buffer->getMacro(
1710 name, *this, false);
1711 d->macro_lock = false;
1717 data = MacroTable::globalMacros().get(name);
1726 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1728 // set scope end behind the last paragraph
1729 DocIterator scope = par_iterator_begin();
1730 scope.pit() = scope.lastpit() + 1;
1732 return getMacro(name, scope, global);
1736 MacroData const * Buffer::getMacro(docstring const & name,
1737 Buffer const & child, bool global) const
1739 // look where the child buffer is included first
1740 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1741 if (it == d->children_positions.end())
1744 // check for macros at the inclusion position
1745 return getMacro(name, it->second, global);
1749 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1751 pit_type lastpit = it.lastpit();
1753 // look for macros in each paragraph
1754 while (it.pit() <= lastpit) {
1755 Paragraph & par = it.paragraph();
1757 // iterate over the insets of the current paragraph
1758 InsetList const & insets = par.insetList();
1759 InsetList::const_iterator iit = insets.begin();
1760 InsetList::const_iterator end = insets.end();
1761 for (; iit != end; ++iit) {
1762 it.pos() = iit->pos;
1764 // is it a nested text inset?
1765 if (iit->inset->asInsetText()) {
1766 // Inset needs its own scope?
1767 InsetText const * itext
1768 = iit->inset->asInsetText();
1769 bool newScope = itext->isMacroScope();
1771 // scope which ends just behind the inset
1772 DocIterator insetScope = it;
1775 // collect macros in inset
1776 it.push_back(CursorSlice(*iit->inset));
1777 updateMacros(it, newScope ? insetScope : scope);
1782 // is it an external file?
1783 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1784 // get buffer of external file
1785 InsetCommand const & inset
1786 = static_cast<InsetCommand const &>(*iit->inset);
1787 InsetCommandParams const & ip = inset.params();
1788 d->macro_lock = true;
1789 Buffer * child = loadIfNeeded(*this, ip);
1790 d->macro_lock = false;
1794 // register its position, but only when it is
1795 // included first in the buffer
1796 if (d->children_positions.find(child)
1797 == d->children_positions.end())
1798 d->children_positions[child] = it;
1800 // register child with its scope
1801 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1805 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1809 MathMacroTemplate & macroTemplate
1810 = static_cast<MathMacroTemplate &>(*iit->inset);
1811 MacroContext mc(*this, it);
1812 macroTemplate.updateToContext(mc);
1815 bool valid = macroTemplate.validMacro();
1816 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1817 // then the BufferView's cursor will be invalid in
1818 // some cases which leads to crashes.
1823 d->macros[macroTemplate.name()][it] =
1824 Impl::ScopeMacro(scope, MacroData(*this, it));
1834 void Buffer::updateMacros() const
1839 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1841 // start with empty table
1843 d->children_positions.clear();
1844 d->position_to_children.clear();
1846 // Iterate over buffer, starting with first paragraph
1847 // The scope must be bigger than any lookup DocIterator
1848 // later. For the global lookup, lastpit+1 is used, hence
1849 // we use lastpit+2 here.
1850 DocIterator it = par_iterator_begin();
1851 DocIterator outerScope = it;
1852 outerScope.pit() = outerScope.lastpit() + 2;
1853 updateMacros(it, outerScope);
1857 void Buffer::updateMacroInstances() const
1859 LYXERR(Debug::MACROS, "updateMacroInstances for "
1860 << d->filename.onlyFileName());
1861 DocIterator it = doc_iterator_begin(inset());
1862 DocIterator end = doc_iterator_end(inset());
1863 for (; it != end; it.forwardPos()) {
1864 // look for MathData cells in InsetMathNest insets
1865 Inset * inset = it.nextInset();
1869 InsetMath * minset = inset->asInsetMath();
1873 // update macro in all cells of the InsetMathNest
1874 DocIterator::idx_type n = minset->nargs();
1875 MacroContext mc = MacroContext(*this, it);
1876 for (DocIterator::idx_type i = 0; i < n; ++i) {
1877 MathData & data = minset->cell(i);
1878 data.updateMacros(0, mc);
1884 void Buffer::listMacroNames(MacroNameSet & macros) const
1889 d->macro_lock = true;
1891 // loop over macro names
1892 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1893 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1894 for (; nameIt != nameEnd; ++nameIt)
1895 macros.insert(nameIt->first);
1897 // loop over children
1898 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1899 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1900 for (; it != end; ++it)
1901 it->first->listMacroNames(macros);
1904 if (d->parent_buffer)
1905 d->parent_buffer->listMacroNames(macros);
1907 d->macro_lock = false;
1911 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1913 if (!d->parent_buffer)
1917 d->parent_buffer->listMacroNames(names);
1920 MacroNameSet::iterator it = names.begin();
1921 MacroNameSet::iterator end = names.end();
1922 for (; it != end; ++it) {
1924 MacroData const * data =
1925 d->parent_buffer->getMacro(*it, *this, false);
1927 macros.insert(data);
1929 // we cannot access the original MathMacroTemplate anymore
1930 // here to calls validate method. So we do its work here manually.
1931 // FIXME: somehow make the template accessible here.
1932 if (data->optionals() > 0)
1933 features.require("xargs");
1939 Buffer::References & Buffer::references(docstring const & label)
1941 if (d->parent_buffer)
1942 return const_cast<Buffer *>(masterBuffer())->references(label);
1944 RefCache::iterator it = d->ref_cache_.find(label);
1945 if (it != d->ref_cache_.end())
1946 return it->second.second;
1948 static InsetLabel const * dummy_il = 0;
1949 static References const dummy_refs;
1950 it = d->ref_cache_.insert(
1951 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
1952 return it->second.second;
1956 Buffer::References const & Buffer::references(docstring const & label) const
1958 return const_cast<Buffer *>(this)->references(label);
1962 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
1964 masterBuffer()->d->ref_cache_[label].first = il;
1968 InsetLabel const * Buffer::insetLabel(docstring const & label) const
1970 return masterBuffer()->d->ref_cache_[label].first;
1974 void Buffer::clearReferenceCache() const
1976 if (!d->parent_buffer)
1977 d->ref_cache_.clear();
1981 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1984 //FIXME: This does not work for child documents yet.
1985 LASSERT(code == CITE_CODE, /**/);
1986 // Check if the label 'from' appears more than once
1987 vector<docstring> labels;
1990 keys.fillWithBibKeys(this);
1991 BiblioInfo::const_iterator bit = keys.begin();
1992 BiblioInfo::const_iterator bend = keys.end();
1994 for (; bit != bend; ++bit)
1996 labels.push_back(bit->first);
1999 if (count(labels.begin(), labels.end(), from) > 1)
2002 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2003 if (it->lyxCode() == code) {
2004 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2005 docstring const oldValue = inset.getParam(paramName);
2006 if (oldValue == from)
2007 inset.setParam(paramName, to);
2013 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2014 pit_type par_end, bool full_source)
2016 OutputParams runparams(¶ms().encoding());
2017 runparams.nice = true;
2018 runparams.flavor = OutputParams::LATEX;
2019 runparams.linelen = lyxrc.plaintext_linelen;
2020 // No side effect of file copying and image conversion
2021 runparams.dryrun = true;
2025 os << "% " << _("Preview source code") << "\n\n";
2026 d->texrow.newline();
2027 d->texrow.newline();
2029 writeLaTeXSource(os, filePath(), runparams, true, true);
2031 writeDocBookSource(os, absFileName(), runparams, false);
2033 runparams.par_begin = par_begin;
2034 runparams.par_end = par_end;
2035 if (par_begin + 1 == par_end) {
2037 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2041 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2042 convert<docstring>(par_begin),
2043 convert<docstring>(par_end - 1))
2046 d->texrow.newline();
2047 d->texrow.newline();
2048 // output paragraphs
2050 latexParagraphs(*this, text(), os, d->texrow, runparams);
2053 docbookParagraphs(paragraphs(), *this, os, runparams);
2058 ErrorList & Buffer::errorList(string const & type) const
2060 static ErrorList emptyErrorList;
2061 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2062 if (I == d->errorLists.end())
2063 return emptyErrorList;
2069 void Buffer::structureChanged() const
2072 gui_->structureChanged();
2076 void Buffer::errors(string const & err) const
2083 void Buffer::message(docstring const & msg) const
2090 void Buffer::setBusy(bool on) const
2097 void Buffer::setReadOnly(bool on) const
2100 d->wa_->setReadOnly(on);
2104 void Buffer::updateTitles() const
2107 d->wa_->updateTitles();
2111 void Buffer::resetAutosaveTimers() const
2114 gui_->resetAutosaveTimers();
2118 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2127 class AutoSaveBuffer : public ForkedProcess {
2130 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2131 : buffer_(buffer), fname_(fname) {}
2133 virtual boost::shared_ptr<ForkedProcess> clone() const
2135 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2140 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2141 from_utf8(fname_.absFilename())));
2142 return run(DontWait);
2146 virtual int generateChild();
2148 Buffer const & buffer_;
2153 int AutoSaveBuffer::generateChild()
2155 // tmp_ret will be located (usually) in /tmp
2156 // will that be a problem?
2157 // Note that this calls ForkedCalls::fork(), so it's
2158 // ok cross-platform.
2159 pid_t const pid = fork();
2160 // If you want to debug the autosave
2161 // you should set pid to -1, and comment out the fork.
2162 if (pid != 0 && pid != -1)
2165 // pid = -1 signifies that lyx was unable
2166 // to fork. But we will do the save
2168 bool failed = false;
2169 FileName const tmp_ret = FileName::tempName("lyxauto");
2170 if (!tmp_ret.empty()) {
2171 buffer_.writeFile(tmp_ret);
2172 // assume successful write of tmp_ret
2173 if (!tmp_ret.moveTo(fname_))
2179 // failed to write/rename tmp_ret so try writing direct
2180 if (!buffer_.writeFile(fname_)) {
2181 // It is dangerous to do this in the child,
2182 // but safe in the parent, so...
2183 if (pid == -1) // emit message signal.
2184 buffer_.message(_("Autosave failed!"));
2188 if (pid == 0) // we are the child so...
2197 // Perfect target for a thread...
2198 void Buffer::autoSave() const
2200 if (isBakClean() || isReadonly()) {
2201 // We don't save now, but we'll try again later
2202 resetAutosaveTimers();
2206 // emit message signal.
2207 message(_("Autosaving current document..."));
2209 // create autosave filename
2210 string fname = filePath();
2212 fname += d->filename.onlyFileName();
2215 AutoSaveBuffer autosave(*this, FileName(fname));
2219 resetAutosaveTimers();
2223 string Buffer::bufferFormat() const
2233 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2234 string & result_file) const
2236 string backend_format;
2237 OutputParams runparams(¶ms().encoding());
2238 runparams.flavor = OutputParams::LATEX;
2239 runparams.linelen = lyxrc.plaintext_linelen;
2240 vector<string> backs = backends();
2241 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2242 // Get shortest path to format
2243 Graph::EdgePath path;
2244 for (vector<string>::const_iterator it = backs.begin();
2245 it != backs.end(); ++it) {
2246 Graph::EdgePath p = theConverters().getPath(*it, format);
2247 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2248 backend_format = *it;
2253 runparams.flavor = theConverters().getFlavor(path);
2255 Alert::error(_("Couldn't export file"),
2256 bformat(_("No information for exporting the format %1$s."),
2257 formats.prettyName(format)));
2261 backend_format = format;
2262 // FIXME: Don't hardcode format names here, but use a flag
2263 if (backend_format == "pdflatex")
2264 runparams.flavor = OutputParams::PDFLATEX;
2267 string filename = latexName(false);
2268 filename = addName(temppath(), filename);
2269 filename = changeExtension(filename,
2270 formats.extension(backend_format));
2273 updateMacroInstances();
2275 // Plain text backend
2276 if (backend_format == "text")
2277 writePlaintextFile(*this, FileName(filename), runparams);
2279 else if (backend_format == "lyx")
2280 writeFile(FileName(filename));
2282 else if (isDocBook()) {
2283 runparams.nice = !put_in_tempdir;
2284 makeDocBookFile(FileName(filename), runparams);
2287 else if (backend_format == format) {
2288 runparams.nice = true;
2289 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2291 } else if (!lyxrc.tex_allows_spaces
2292 && contains(filePath(), ' ')) {
2293 Alert::error(_("File name error"),
2294 _("The directory path to the document cannot contain spaces."));
2297 runparams.nice = false;
2298 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2302 string const error_type = (format == "program")
2303 ? "Build" : bufferFormat();
2304 string const ext = formats.extension(format);
2305 FileName const tmp_result_file(changeExtension(filename, ext));
2306 bool const success = theConverters().convert(this, FileName(filename),
2307 tmp_result_file, FileName(absFileName()), backend_format, format,
2308 errorList(error_type));
2309 // Emit the signal to show the error list.
2310 if (format != backend_format)
2315 if (put_in_tempdir) {
2316 result_file = tmp_result_file.absFilename();
2320 result_file = changeExtension(absFileName(), ext);
2321 // We need to copy referenced files (e. g. included graphics
2322 // if format == "dvi") to the result dir.
2323 vector<ExportedFile> const files =
2324 runparams.exportdata->externalFiles(format);
2325 string const dest = onlyPath(result_file);
2326 CopyStatus status = SUCCESS;
2327 for (vector<ExportedFile>::const_iterator it = files.begin();
2328 it != files.end() && status != CANCEL; ++it) {
2329 string const fmt = formats.getFormatFromFile(it->sourceName);
2330 status = copyFile(fmt, it->sourceName,
2331 makeAbsPath(it->exportName, dest),
2332 it->exportName, status == FORCE);
2334 if (status == CANCEL) {
2335 message(_("Document export cancelled."));
2336 } else if (tmp_result_file.exists()) {
2337 // Finally copy the main file
2338 status = copyFile(format, tmp_result_file,
2339 FileName(result_file), result_file,
2341 message(bformat(_("Document exported as %1$s "
2343 formats.prettyName(format),
2344 makeDisplayPath(result_file)));
2346 // This must be a dummy converter like fax (bug 1888)
2347 message(bformat(_("Document exported as %1$s"),
2348 formats.prettyName(format)));
2355 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2358 return doExport(format, put_in_tempdir, result_file);
2362 bool Buffer::preview(string const & format) const
2365 if (!doExport(format, true, result_file))
2367 return formats.view(*this, FileName(result_file), format);
2371 bool Buffer::isExportable(string const & format) const
2373 vector<string> backs = backends();
2374 for (vector<string>::const_iterator it = backs.begin();
2375 it != backs.end(); ++it)
2376 if (theConverters().isReachable(*it, format))
2382 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2384 vector<string> backs = backends();
2385 vector<Format const *> result =
2386 theConverters().getReachable(backs[0], only_viewable, true);
2387 for (vector<string>::const_iterator it = backs.begin() + 1;
2388 it != backs.end(); ++it) {
2389 vector<Format const *> r =
2390 theConverters().getReachable(*it, only_viewable, false);
2391 result.insert(result.end(), r.begin(), r.end());
2397 vector<string> Buffer::backends() const
2400 if (params().baseClass()->isTeXClassAvailable()) {
2401 v.push_back(bufferFormat());
2402 // FIXME: Don't hardcode format names here, but use a flag
2403 if (v.back() == "latex")
2404 v.push_back("pdflatex");
2406 v.push_back("text");
2412 bool Buffer::readFileHelper(FileName const & s)
2414 // File information about normal file
2416 docstring const file = makeDisplayPath(s.absFilename(), 50);
2417 docstring text = bformat(_("The specified document\n%1$s"
2418 "\ncould not be read."), file);
2419 Alert::error(_("Could not read document"), text);
2423 // Check if emergency save file exists and is newer.
2424 FileName const e(s.absFilename() + ".emergency");
2426 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2427 docstring const file = makeDisplayPath(s.absFilename(), 20);
2428 docstring const text =
2429 bformat(_("An emergency save of the document "
2431 "Recover emergency save?"), file);
2432 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2433 _("&Recover"), _("&Load Original"),
2437 // the file is not saved if we load the emergency file.
2447 // Now check if autosave file is newer.
2448 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2450 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2451 docstring const file = makeDisplayPath(s.absFilename(), 20);
2452 docstring const text =
2453 bformat(_("The backup of the document "
2454 "%1$s is newer.\n\nLoad the "
2455 "backup instead?"), file);
2456 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2457 _("&Load backup"), _("Load &original"),
2461 // the file is not saved if we load the autosave file.
2465 // Here we delete the autosave
2476 bool Buffer::loadLyXFile(FileName const & s)
2478 if (s.isReadableFile()) {
2479 if (readFileHelper(s)) {
2480 lyxvc().file_found_hook(s);
2481 if (!s.isWritable())
2486 docstring const file = makeDisplayPath(s.absFilename(), 20);
2487 // Here we probably should run
2488 if (LyXVC::file_not_found_hook(s)) {
2489 docstring const text =
2490 bformat(_("Do you want to retrieve the document"
2491 " %1$s from version control?"), file);
2492 int const ret = Alert::prompt(_("Retrieve from version control?"),
2493 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2496 // How can we know _how_ to do the checkout?
2497 // With the current VC support it has to be,
2498 // a RCS file since CVS do not have special ,v files.
2500 return loadLyXFile(s);
2508 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2510 TeXErrors::Errors::const_iterator cit = terr.begin();
2511 TeXErrors::Errors::const_iterator end = terr.end();
2513 for (; cit != end; ++cit) {
2516 int errorRow = cit->error_in_line;
2517 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2523 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2524 } while (found && id_start == id_end && pos_start == pos_end);
2526 errorList.push_back(ErrorItem(cit->error_desc,
2527 cit->error_text, id_start, pos_start, pos_end));