3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 370; // uwestoehr: option to suppress default date
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer & parent, FileName const & file, bool readonly);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfilesCache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfoCacheValid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfileStatus_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 if (!theBufferList().isLoaded(parent_buffer))
253 return parent_buffer;
256 void setParent(Buffer const * pb) { parent_buffer = pb; }
258 /// So we can force access via the accessors.
259 mutable Buffer const * parent_buffer;
263 /// Creates the per buffer temporary directory
264 static FileName createBufferTmpDir()
267 // We are in our own directory. Why bother to mangle name?
268 // In fact I wrote this code to circumvent a problematic behaviour
269 // (bug?) of EMX mkstemp().
270 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
271 convert<string>(count++));
273 if (!tmpfl.createDirectory(0777)) {
274 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
275 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
276 from_utf8(tmpfl.absFilename())));
282 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
283 : lyx_clean(true), bak_clean(true), unnamed(false),
284 read_only(readonly_), filename(file), file_fully_loaded(false),
285 toc_backend(&parent), macro_lock(false), timestamp_(0),
286 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
289 temppath = createBufferTmpDir();
290 lyxvc.setBuffer(&parent);
292 wa_ = new frontend::WorkAreaManager;
296 Buffer::Buffer(string const & file, bool readonly)
297 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
299 LYXERR(Debug::INFO, "Buffer::Buffer()");
301 d->inset = new InsetText(*this);
302 d->inset->setAutoBreakRows(true);
303 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
309 LYXERR(Debug::INFO, "Buffer::~Buffer()");
310 // here the buffer should take care that it is
311 // saved properly, before it goes into the void.
313 // GuiView already destroyed
317 // No need to do additional cleanups for internal buffer.
322 // loop over children
323 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
324 Impl::BufferPositionMap::iterator end = d->children_positions.end();
325 for (; it != end; ++it) {
326 Buffer * child = const_cast<Buffer *>(it->first);
327 // The child buffer might have been closed already.
328 if (theBufferList().isLoaded(child))
329 theBufferList().releaseChild(this, child);
333 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
334 msg += emergencyWrite();
335 frontend::Alert::warning(_("Attempting to close changed document!"), msg);
338 // clear references to children in macro tables
339 d->children_positions.clear();
340 d->position_to_children.clear();
342 if (!d->temppath.destroyDirectory()) {
343 Alert::warning(_("Could not remove temporary directory"),
344 bformat(_("Could not remove the temporary directory %1$s"),
345 from_utf8(d->temppath.absFilename())));
348 // Remove any previewed LaTeX snippets associated with this buffer.
349 thePreviews().removeLoader(*this);
355 void Buffer::changed() const
362 frontend::WorkAreaManager & Buffer::workAreaManager() const
364 LASSERT(d->wa_, /**/);
369 Text & Buffer::text() const
371 return d->inset->text();
375 Inset & Buffer::inset() const
381 BufferParams & Buffer::params()
387 BufferParams const & Buffer::params() const
393 ParagraphList & Buffer::paragraphs()
395 return text().paragraphs();
399 ParagraphList const & Buffer::paragraphs() const
401 return text().paragraphs();
405 LyXVC & Buffer::lyxvc()
411 LyXVC const & Buffer::lyxvc() const
417 string const Buffer::temppath() const
419 return d->temppath.absFilename();
423 TexRow & Buffer::texrow()
429 TexRow const & Buffer::texrow() const
435 TocBackend & Buffer::tocBackend() const
437 return d->toc_backend;
441 Undo & Buffer::undo()
447 string Buffer::latexName(bool const no_path) const
449 FileName latex_name =
450 makeLatexName(exportFileName());
451 return no_path ? latex_name.onlyFileName()
452 : latex_name.absFilename();
456 FileName Buffer::exportFileName() const
458 docstring const branch_suffix =
459 params().branchlist().getFilenameSuffix();
460 if (branch_suffix.empty())
463 string const name = fileName().onlyFileNameWithoutExt()
464 + to_utf8(branch_suffix);
465 FileName res(fileName().onlyPath().absFilename() + "/" + name);
466 res.changeExtension(fileName().extension());
472 string Buffer::logName(LogType * type) const
474 string const filename = latexName(false);
476 if (filename.empty()) {
482 string const path = temppath();
484 FileName const fname(addName(temppath(),
485 onlyFilename(changeExtension(filename,
488 // FIXME: how do we know this is the name of the build log?
489 FileName const bname(
490 addName(path, onlyFilename(
491 changeExtension(filename,
492 formats.extension(bufferFormat()) + ".out"))));
494 // Also consider the master buffer log file
495 FileName masterfname = fname;
497 if (masterBuffer() != this) {
498 string const mlogfile = masterBuffer()->logName(&mtype);
499 masterfname = FileName(mlogfile);
502 // If no Latex log or Build log is newer, show Build log
503 if (bname.exists() &&
504 ((!fname.exists() && !masterfname.exists())
505 || (fname.lastModified() < bname.lastModified()
506 && masterfname.lastModified() < bname.lastModified()))) {
507 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
510 return bname.absFilename();
511 // If we have a newer master file log or only a master log, show this
512 } else if (fname != masterfname
513 && (!fname.exists() && (masterfname.exists()
514 || fname.lastModified() < masterfname.lastModified()))) {
515 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
518 return masterfname.absFilename();
520 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
523 return fname.absFilename();
527 void Buffer::setReadonly(bool const flag)
529 if (d->read_only != flag) {
536 void Buffer::setFileName(string const & newfile)
538 d->filename = makeAbsPath(newfile);
539 setReadonly(d->filename.isReadOnly());
544 int Buffer::readHeader(Lexer & lex)
546 int unknown_tokens = 0;
548 int begin_header_line = -1;
550 // Initialize parameters that may be/go lacking in header:
551 params().branchlist().clear();
552 params().preamble.erase();
553 params().options.erase();
554 params().master.erase();
555 params().float_placement.erase();
556 params().paperwidth.erase();
557 params().paperheight.erase();
558 params().leftmargin.erase();
559 params().rightmargin.erase();
560 params().topmargin.erase();
561 params().bottommargin.erase();
562 params().headheight.erase();
563 params().headsep.erase();
564 params().footskip.erase();
565 params().columnsep.erase();
566 params().fontsCJK.erase();
567 params().listings_params.clear();
568 params().clearLayoutModules();
569 params().clearRemovedModules();
570 params().pdfoptions().clear();
571 params().indiceslist().clear();
572 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
574 for (int i = 0; i < 4; ++i) {
575 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
576 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
579 ErrorList & errorList = d->errorLists["Parse"];
588 if (token == "\\end_header")
592 if (token == "\\begin_header") {
593 begin_header_line = line;
597 LYXERR(Debug::PARSER, "Handling document header token: `"
600 string unknown = params().readToken(lex, token, d->filename.onlyPath());
601 if (!unknown.empty()) {
602 if (unknown[0] != '\\' && token == "\\textclass") {
603 Alert::warning(_("Unknown document class"),
604 bformat(_("Using the default document class, because the "
605 "class %1$s is unknown."), from_utf8(unknown)));
608 docstring const s = bformat(_("Unknown token: "
612 errorList.push_back(ErrorItem(_("Document header error"),
617 if (begin_header_line) {
618 docstring const s = _("\\begin_header is missing");
619 errorList.push_back(ErrorItem(_("Document header error"),
623 params().makeDocumentClass();
625 return unknown_tokens;
630 // changed to be public and have one parameter
631 // Returns true if "\end_document" is not read (Asger)
632 bool Buffer::readDocument(Lexer & lex)
634 ErrorList & errorList = d->errorLists["Parse"];
637 if (!lex.checkFor("\\begin_document")) {
638 docstring const s = _("\\begin_document is missing");
639 errorList.push_back(ErrorItem(_("Document header error"),
643 // we are reading in a brand new document
644 LASSERT(paragraphs().empty(), /**/);
648 if (params().outputChanges) {
649 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
650 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
651 LaTeXFeatures::isAvailable("xcolor");
653 if (!dvipost && !xcolorulem) {
654 Alert::warning(_("Changes not shown in LaTeX output"),
655 _("Changes will not be highlighted in LaTeX output, "
656 "because neither dvipost nor xcolor/ulem are installed.\n"
657 "Please install these packages or redefine "
658 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
659 } else if (!xcolorulem) {
660 Alert::warning(_("Changes not shown in LaTeX output"),
661 _("Changes will not be highlighted in LaTeX output "
662 "when using pdflatex, because xcolor and ulem are not installed.\n"
663 "Please install both packages or redefine "
664 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
668 if (!params().master.empty()) {
669 FileName const master_file = makeAbsPath(params().master,
670 onlyPath(absFileName()));
671 if (isLyXFilename(master_file.absFilename())) {
673 checkAndLoadLyXFile(master_file, true);
675 // necessary e.g. after a reload
676 // to re-register the child (bug 5873)
677 // FIXME: clean up updateMacros (here, only
678 // child registering is needed).
679 master->updateMacros();
680 // set master as master buffer, but only
681 // if we are a real child
682 if (master->isChild(this))
684 // if the master is not fully loaded
685 // it is probably just loading this
686 // child. No warning needed then.
687 else if (master->isFullyLoaded())
688 LYXERR0("The master '"
690 << "' assigned to this document ("
692 << ") does not include "
693 "this document. Ignoring the master assignment.");
698 // assure we have a default index
699 params().indiceslist().addDefault(B_("Index"));
702 bool const res = text().read(lex, errorList, d->inset);
705 updateMacroInstances();
710 bool Buffer::readString(string const & s)
712 params().compressed = false;
714 // remove dummy empty par
715 paragraphs().clear();
719 FileName const name = FileName::tempName("Buffer_readString");
720 switch (readFile(lex, name, true)) {
724 // We need to call lyx2lyx, so write the input to a file
725 ofstream os(name.toFilesystemEncoding().c_str());
728 return readFile(name);
738 bool Buffer::readFile(FileName const & filename)
740 FileName fname(filename);
742 params().compressed = fname.isZippedFile();
744 // remove dummy empty par
745 paragraphs().clear();
748 if (readFile(lex, fname) != success)
755 bool Buffer::isFullyLoaded() const
757 return d->file_fully_loaded;
761 void Buffer::setFullyLoaded(bool value)
763 d->file_fully_loaded = value;
767 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
770 LASSERT(!filename.empty(), /**/);
772 // the first (non-comment) token _must_ be...
773 if (!lex.checkFor("\\lyxformat")) {
774 Alert::error(_("Document format failure"),
775 bformat(_("%1$s is not a readable LyX document."),
776 from_utf8(filename.absFilename())));
782 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
783 // if present remove ".," from string.
784 size_t dot = tmp_format.find_first_of(".,");
785 //lyxerr << " dot found at " << dot << endl;
786 if (dot != string::npos)
787 tmp_format.erase(dot, 1);
788 int const file_format = convert<int>(tmp_format);
789 //lyxerr << "format: " << file_format << endl;
791 // save timestamp and checksum of the original disk file, making sure
792 // to not overwrite them with those of the file created in the tempdir
793 // when it has to be converted to the current format.
795 // Save the timestamp and checksum of disk file. If filename is an
796 // emergency file, save the timestamp and checksum of the original lyx file
797 // because isExternallyModified will check for this file. (BUG4193)
798 string diskfile = filename.absFilename();
799 if (suffixIs(diskfile, ".emergency"))
800 diskfile = diskfile.substr(0, diskfile.size() - 10);
801 saveCheckSum(FileName(diskfile));
804 if (file_format != LYX_FORMAT) {
807 // lyx2lyx would fail
810 FileName const tmpfile = FileName::tempName("Buffer_readFile");
811 if (tmpfile.empty()) {
812 Alert::error(_("Conversion failed"),
813 bformat(_("%1$s is from a different"
814 " version of LyX, but a temporary"
815 " file for converting it could"
817 from_utf8(filename.absFilename())));
820 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
821 if (lyx2lyx.empty()) {
822 Alert::error(_("Conversion script not found"),
823 bformat(_("%1$s is from a different"
824 " version of LyX, but the"
825 " conversion script lyx2lyx"
826 " could not be found."),
827 from_utf8(filename.absFilename())));
830 ostringstream command;
831 command << os::python()
832 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
833 << " -t " << convert<string>(LYX_FORMAT)
834 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
835 << ' ' << quoteName(filename.toFilesystemEncoding());
836 string const command_str = command.str();
838 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
840 cmd_ret const ret = runCommand(command_str);
841 if (ret.first != 0) {
842 Alert::error(_("Conversion script failed"),
843 bformat(_("%1$s is from a different version"
844 " of LyX, but the lyx2lyx script"
845 " failed to convert it."),
846 from_utf8(filename.absFilename())));
849 bool const ret = readFile(tmpfile);
850 // Do stuff with tmpfile name and buffer name here.
851 return ret ? success : failure;
856 if (readDocument(lex)) {
857 Alert::error(_("Document format failure"),
858 bformat(_("%1$s ended unexpectedly, which means"
859 " that it is probably corrupted."),
860 from_utf8(filename.absFilename())));
863 d->file_fully_loaded = true;
868 // Should probably be moved to somewhere else: BufferView? LyXView?
869 bool Buffer::save() const
871 // We don't need autosaves in the immediate future. (Asger)
872 resetAutosaveTimers();
874 string const encodedFilename = d->filename.toFilesystemEncoding();
877 bool madeBackup = false;
879 // make a backup if the file already exists
880 if (lyxrc.make_backup && fileName().exists()) {
881 backupName = FileName(absFileName() + '~');
882 if (!lyxrc.backupdir_path.empty()) {
883 string const mangledName =
884 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
885 backupName = FileName(addName(lyxrc.backupdir_path,
888 if (fileName().copyTo(backupName)) {
891 Alert::error(_("Backup failure"),
892 bformat(_("Cannot create backup file %1$s.\n"
893 "Please check whether the directory exists and is writeable."),
894 from_utf8(backupName.absFilename())));
895 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
899 // ask if the disk file has been externally modified (use checksum method)
900 if (fileName().exists() && isExternallyModified(checksum_method)) {
901 docstring const file = makeDisplayPath(absFileName(), 20);
902 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
903 "you want to overwrite this file?"), file);
904 int const ret = Alert::prompt(_("Overwrite modified file?"),
905 text, 1, 1, _("&Overwrite"), _("&Cancel"));
910 if (writeFile(d->filename)) {
914 // Saving failed, so backup is not backup
916 backupName.moveTo(d->filename);
922 bool Buffer::writeFile(FileName const & fname) const
924 if (d->read_only && fname == d->filename)
929 docstring const str = bformat(_("Saving document %1$s..."),
930 makeDisplayPath(fname.absFilename()));
933 if (params().compressed) {
934 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
935 retval = ofs && write(ofs);
937 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
938 retval = ofs && write(ofs);
942 message(str + _(" could not write file!"));
946 removeAutosaveFile();
948 saveCheckSum(d->filename);
949 message(str + _(" done."));
955 docstring Buffer::emergencyWrite()
957 // No need to save if the buffer has not changed.
961 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
963 docstring user_message = bformat(
964 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
966 // We try to save three places:
967 // 1) Same place as document. Unless it is an unnamed doc.
969 string s = absFileName();
972 if (writeFile(FileName(s))) {
974 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
977 user_message += _(" Save failed! Trying again...\n");
981 // 2) In HOME directory.
982 string s = addName(package().home_dir().absFilename(), absFileName());
984 lyxerr << ' ' << s << endl;
985 if (writeFile(FileName(s))) {
987 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
991 user_message += _(" Save failed! Trying yet again...\n");
993 // 3) In "/tmp" directory.
994 // MakeAbsPath to prepend the current
995 // drive letter on OS/2
996 s = addName(package().temp_dir().absFilename(), absFileName());
998 lyxerr << ' ' << s << endl;
999 if (writeFile(FileName(s))) {
1001 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1002 return user_message;
1005 user_message += _(" Save failed! Bummer. Document is lost.");
1008 return user_message;
1012 bool Buffer::write(ostream & ofs) const
1015 // Use the standard "C" locale for file output.
1016 ofs.imbue(locale::classic());
1019 // The top of the file should not be written by params().
1021 // write out a comment in the top of the file
1022 ofs << "#LyX " << lyx_version
1023 << " created this file. For more info see http://www.lyx.org/\n"
1024 << "\\lyxformat " << LYX_FORMAT << "\n"
1025 << "\\begin_document\n";
1027 /// For each author, set 'used' to true if there is a change
1028 /// by this author in the document; otherwise set it to 'false'.
1029 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1030 AuthorList::Authors::const_iterator a_end = params().authors().end();
1031 for (; a_it != a_end; ++a_it)
1032 a_it->setUsed(false);
1034 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1035 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1036 for ( ; it != end; ++it)
1037 it->checkAuthors(params().authors());
1039 // now write out the buffer parameters.
1040 ofs << "\\begin_header\n";
1041 params().writeFile(ofs);
1042 ofs << "\\end_header\n";
1045 ofs << "\n\\begin_body\n";
1047 ofs << "\n\\end_body\n";
1049 // Write marker that shows file is complete
1050 ofs << "\\end_document" << endl;
1052 // Shouldn't really be needed....
1055 // how to check if close went ok?
1056 // Following is an attempt... (BE 20001011)
1058 // good() returns false if any error occured, including some
1059 // formatting error.
1060 // bad() returns true if something bad happened in the buffer,
1061 // which should include file system full errors.
1066 lyxerr << "File was not closed properly." << endl;
1073 bool Buffer::makeLaTeXFile(FileName const & fname,
1074 string const & original_path,
1075 OutputParams const & runparams_in,
1076 bool output_preamble, bool output_body) const
1078 OutputParams runparams = runparams_in;
1079 if (params().useXetex)
1080 runparams.flavor = OutputParams::XETEX;
1082 string const encoding = runparams.encoding->iconvName();
1083 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1086 try { ofs.reset(encoding); }
1087 catch (iconv_codecvt_facet_exception & e) {
1088 lyxerr << "Caught iconv exception: " << e.what() << endl;
1089 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1090 "verify that the support software for your encoding (%1$s) is "
1091 "properly installed"), from_ascii(encoding)));
1094 if (!openFileWrite(ofs, fname))
1097 //TexStream ts(ofs.rdbuf(), &texrow());
1098 ErrorList & errorList = d->errorLists["Export"];
1100 bool failed_export = false;
1103 writeLaTeXSource(ofs, original_path,
1104 runparams, output_preamble, output_body);
1106 catch (EncodingException & e) {
1107 odocstringstream ods;
1108 ods.put(e.failed_char);
1110 oss << "0x" << hex << e.failed_char << dec;
1111 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1112 " (code point %2$s)"),
1113 ods.str(), from_utf8(oss.str()));
1114 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1115 "representable in the chosen encoding.\n"
1116 "Changing the document encoding to utf8 could help."),
1117 e.par_id, e.pos, e.pos + 1));
1118 failed_export = true;
1120 catch (iconv_codecvt_facet_exception & e) {
1121 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1122 _(e.what()), -1, 0, 0));
1123 failed_export = true;
1125 catch (exception const & e) {
1126 errorList.push_back(ErrorItem(_("conversion failed"),
1127 _(e.what()), -1, 0, 0));
1128 failed_export = true;
1131 lyxerr << "Caught some really weird exception..." << endl;
1137 failed_export = true;
1138 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1142 return !failed_export;
1146 void Buffer::writeLaTeXSource(odocstream & os,
1147 string const & original_path,
1148 OutputParams const & runparams_in,
1149 bool const output_preamble, bool const output_body) const
1151 // The child documents, if any, shall be already loaded at this point.
1153 OutputParams runparams = runparams_in;
1155 // Classify the unicode characters appearing in math insets
1156 Encodings::initUnicodeMath(*this);
1158 // validate the buffer.
1159 LYXERR(Debug::LATEX, " Validating buffer...");
1160 LaTeXFeatures features(*this, params(), runparams);
1162 LYXERR(Debug::LATEX, " Buffer validation done.");
1164 // The starting paragraph of the coming rows is the
1165 // first paragraph of the document. (Asger)
1166 if (output_preamble && runparams.nice) {
1167 os << "%% LyX " << lyx_version << " created this file. "
1168 "For more info, see http://www.lyx.org/.\n"
1169 "%% Do not edit unless you really know what "
1171 d->texrow.newline();
1172 d->texrow.newline();
1174 LYXERR(Debug::INFO, "lyx document header finished");
1176 // Don't move this behind the parent_buffer=0 code below,
1177 // because then the macros will not get the right "redefinition"
1178 // flag as they don't see the parent macros which are output before.
1181 // fold macros if possible, still with parent buffer as the
1182 // macros will be put in the prefix anyway.
1183 updateMacroInstances();
1185 // There are a few differences between nice LaTeX and usual files:
1186 // usual is \batchmode and has a
1187 // special input@path to allow the including of figures
1188 // with either \input or \includegraphics (what figinsets do).
1189 // input@path is set when the actual parameter
1190 // original_path is set. This is done for usual tex-file, but not
1191 // for nice-latex-file. (Matthias 250696)
1192 // Note that input@path is only needed for something the user does
1193 // in the preamble, included .tex files or ERT, files included by
1194 // LyX work without it.
1195 if (output_preamble) {
1196 if (!runparams.nice) {
1197 // code for usual, NOT nice-latex-file
1198 os << "\\batchmode\n"; // changed
1199 // from \nonstopmode
1200 d->texrow.newline();
1202 if (!original_path.empty()) {
1204 // We don't know the encoding of inputpath
1205 docstring const inputpath = from_utf8(latex_path(original_path));
1206 os << "\\makeatletter\n"
1207 << "\\def\\input@path{{"
1208 << inputpath << "/}}\n"
1209 << "\\makeatother\n";
1210 d->texrow.newline();
1211 d->texrow.newline();
1212 d->texrow.newline();
1215 // get parent macros (if this buffer has a parent) which will be
1216 // written at the document begin further down.
1217 MacroSet parentMacros;
1218 listParentMacros(parentMacros, features);
1220 // Write the preamble
1221 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1223 runparams.use_japanese = features.isRequired("japanese");
1229 os << "\\begin{document}\n";
1230 d->texrow.newline();
1232 // output the parent macros
1233 MacroSet::iterator it = parentMacros.begin();
1234 MacroSet::iterator end = parentMacros.end();
1235 for (; it != end; ++it)
1236 (*it)->write(os, true);
1237 } // output_preamble
1239 d->texrow.start(paragraphs().begin()->id(), 0);
1241 LYXERR(Debug::INFO, "preamble finished, now the body.");
1243 // if we are doing a real file with body, even if this is the
1244 // child of some other buffer, let's cut the link here.
1245 // This happens for example if only a child document is printed.
1246 Buffer const * save_parent = 0;
1247 if (output_preamble) {
1248 save_parent = d->parent();
1253 latexParagraphs(*this, text(), os, d->texrow, runparams);
1255 // Restore the parenthood if needed
1256 if (output_preamble)
1257 d->setParent(save_parent);
1259 // add this just in case after all the paragraphs
1261 d->texrow.newline();
1263 if (output_preamble) {
1264 os << "\\end{document}\n";
1265 d->texrow.newline();
1266 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1268 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1270 runparams_in.encoding = runparams.encoding;
1272 // Just to be sure. (Asger)
1273 d->texrow.newline();
1275 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1276 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1280 bool Buffer::isLatex() const
1282 return params().documentClass().outputType() == LATEX;
1286 bool Buffer::isLiterate() const
1288 return params().documentClass().outputType() == LITERATE;
1292 bool Buffer::isDocBook() const
1294 return params().documentClass().outputType() == DOCBOOK;
1298 void Buffer::makeDocBookFile(FileName const & fname,
1299 OutputParams const & runparams,
1300 bool const body_only) const
1302 LYXERR(Debug::LATEX, "makeDocBookFile...");
1305 if (!openFileWrite(ofs, fname))
1308 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1312 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1316 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1317 OutputParams const & runparams,
1318 bool const only_body) const
1320 LaTeXFeatures features(*this, params(), runparams);
1325 DocumentClass const & tclass = params().documentClass();
1326 string const top_element = tclass.latexname();
1329 if (runparams.flavor == OutputParams::XML)
1330 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1333 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1336 if (! tclass.class_header().empty())
1337 os << from_ascii(tclass.class_header());
1338 else if (runparams.flavor == OutputParams::XML)
1339 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1340 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1342 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1344 docstring preamble = from_utf8(params().preamble);
1345 if (runparams.flavor != OutputParams::XML ) {
1346 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1347 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1348 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1349 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1352 string const name = runparams.nice
1353 ? changeExtension(absFileName(), ".sgml") : fname;
1354 preamble += features.getIncludedFiles(name);
1355 preamble += features.getLyXSGMLEntities();
1357 if (!preamble.empty()) {
1358 os << "\n [ " << preamble << " ]";
1363 string top = top_element;
1365 if (runparams.flavor == OutputParams::XML)
1366 top += params().language->code();
1368 top += params().language->code().substr(0, 2);
1371 if (!params().options.empty()) {
1373 top += params().options;
1376 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1377 << " file was created by LyX " << lyx_version
1378 << "\n See http://www.lyx.org/ for more information -->\n";
1380 params().documentClass().counters().reset();
1384 sgml::openTag(os, top);
1386 docbookParagraphs(text(), *this, os, runparams);
1387 sgml::closeTag(os, top_element);
1391 void Buffer::makeLyXHTMLFile(FileName const & fname,
1392 OutputParams const & runparams,
1393 bool const body_only) const
1395 LYXERR(Debug::LATEX, "makeLYXHTMLFile...");
1398 if (!openFileWrite(ofs, fname))
1401 writeLyXHTMLSource(ofs, runparams, body_only);
1405 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1409 void Buffer::writeLyXHTMLSource(odocstream & os,
1410 OutputParams const & runparams,
1411 bool const only_body) const
1413 LaTeXFeatures features(*this, params(), runparams);
1419 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" <<
1420 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1421 // FIXME Language should be set properly.
1422 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n";
1425 // FIXME Presumably need to set this right
1426 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1427 // FIXME Get this during validation? What about other meta-data?
1428 os << "<title>TBA</title>\n";
1430 os << features.getTClassHTMLPreamble();
1434 docstring const styleinfo = features.getTClassHTMLStyles();
1435 if (!styleinfo.empty()) {
1436 os << "<style type='text/css'>\n";
1440 os << "</head>\n<body>\n";
1443 params().documentClass().counters().reset();
1444 xhtmlParagraphs(text(), *this, os, runparams);
1446 os << "</body>\n</html>\n";
1450 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1451 // Other flags: -wall -v0 -x
1452 int Buffer::runChktex()
1456 // get LaTeX-Filename
1457 FileName const path(temppath());
1458 string const name = addName(path.absFilename(), latexName());
1459 string const org_path = filePath();
1461 PathChanger p(path); // path to LaTeX file
1462 message(_("Running chktex..."));
1464 // Generate the LaTeX file if neccessary
1465 OutputParams runparams(¶ms().encoding());
1466 runparams.flavor = OutputParams::LATEX;
1467 runparams.nice = false;
1468 makeLaTeXFile(FileName(name), org_path, runparams);
1471 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1472 int const res = chktex.run(terr); // run chktex
1475 Alert::error(_("chktex failure"),
1476 _("Could not run chktex successfully."));
1477 } else if (res > 0) {
1478 ErrorList & errlist = d->errorLists["ChkTeX"];
1480 bufferErrors(terr, errlist);
1491 void Buffer::validate(LaTeXFeatures & features) const
1493 params().validate(features);
1497 for_each(paragraphs().begin(), paragraphs().end(),
1498 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1500 if (lyxerr.debugging(Debug::LATEX)) {
1501 features.showStruct();
1506 void Buffer::getLabelList(vector<docstring> & list) const
1508 // If this is a child document, use the parent's list instead.
1509 Buffer const * const pbuf = d->parent();
1511 pbuf->getLabelList(list);
1516 Toc & toc = d->toc_backend.toc("label");
1517 TocIterator toc_it = toc.begin();
1518 TocIterator end = toc.end();
1519 for (; toc_it != end; ++toc_it) {
1520 if (toc_it->depth() == 0)
1521 list.push_back(toc_it->str());
1526 void Buffer::updateBibfilesCache(UpdateScope scope) const
1528 // If this is a child document, use the parent's cache instead.
1529 Buffer const * const pbuf = d->parent();
1530 if (pbuf && scope != UpdateChildOnly) {
1531 pbuf->updateBibfilesCache();
1535 d->bibfilesCache_.clear();
1536 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1537 if (it->lyxCode() == BIBTEX_CODE) {
1538 InsetBibtex const & inset =
1539 static_cast<InsetBibtex const &>(*it);
1540 support::FileNameList const bibfiles = inset.getBibFiles();
1541 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1544 } else if (it->lyxCode() == INCLUDE_CODE) {
1545 InsetInclude & inset =
1546 static_cast<InsetInclude &>(*it);
1547 inset.updateBibfilesCache();
1548 support::FileNameList const & bibfiles =
1549 inset.getBibfilesCache();
1550 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1555 // the bibinfo cache is now invalid
1556 d->bibinfoCacheValid_ = false;
1560 void Buffer::invalidateBibinfoCache()
1562 d->bibinfoCacheValid_ = false;
1566 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1568 // If this is a child document, use the parent's cache instead.
1569 Buffer const * const pbuf = d->parent();
1570 if (pbuf && scope != UpdateChildOnly)
1571 return pbuf->getBibfilesCache();
1573 // We update the cache when first used instead of at loading time.
1574 if (d->bibfilesCache_.empty())
1575 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1577 return d->bibfilesCache_;
1581 BiblioInfo const & Buffer::masterBibInfo() const
1583 // if this is a child document and the parent is already loaded
1584 // use the parent's list instead [ale990412]
1585 Buffer const * const tmp = masterBuffer();
1588 return tmp->masterBibInfo();
1589 return localBibInfo();
1593 BiblioInfo const & Buffer::localBibInfo() const
1595 if (d->bibinfoCacheValid_) {
1596 support::FileNameList const & bibfilesCache = getBibfilesCache();
1597 // compare the cached timestamps with the actual ones.
1598 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1599 support::FileNameList::const_iterator en = bibfilesCache.end();
1600 for (; ei != en; ++ ei) {
1601 time_t lastw = ei->lastModified();
1602 if (lastw != d->bibfileStatus_[*ei]) {
1603 d->bibinfoCacheValid_ = false;
1604 d->bibfileStatus_[*ei] = lastw;
1610 if (!d->bibinfoCacheValid_) {
1611 d->bibinfo_.clear();
1612 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1613 it->fillWithBibKeys(d->bibinfo_, it);
1614 d->bibinfoCacheValid_ = true;
1620 bool Buffer::isDepClean(string const & name) const
1622 DepClean::const_iterator const it = d->dep_clean.find(name);
1623 if (it == d->dep_clean.end())
1629 void Buffer::markDepClean(string const & name)
1631 d->dep_clean[name] = true;
1635 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1638 // FIXME? if there is an Buffer LFUN that can be dispatched even
1639 // if internal, put a switch '(cmd.action)' here.
1645 switch (cmd.action) {
1647 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1648 flag.setOnOff(isReadonly());
1651 // FIXME: There is need for a command-line import.
1652 //case LFUN_BUFFER_IMPORT:
1654 case LFUN_BUFFER_AUTO_SAVE:
1657 case LFUN_BUFFER_EXPORT_CUSTOM:
1658 // FIXME: Nothing to check here?
1661 case LFUN_BUFFER_EXPORT: {
1662 docstring const arg = cmd.argument();
1663 enable = arg == "custom" || isExportable(to_utf8(arg));
1665 flag.message(bformat(
1666 _("Don't know how to export to format: %1$s"), arg));
1670 case LFUN_MASTER_BUFFER_UPDATE:
1671 case LFUN_MASTER_BUFFER_VIEW:
1672 enable = parent() != 0;
1674 case LFUN_BUFFER_UPDATE:
1675 case LFUN_BUFFER_VIEW: {
1676 string format = to_utf8(cmd.argument());
1677 if (cmd.argument().empty())
1678 format = getDefaultOutputFormat();
1679 typedef vector<Format const *> Formats;
1681 formats = exportableFormats(true);
1682 Formats::const_iterator fit = formats.begin();
1683 Formats::const_iterator end = formats.end();
1685 for (; fit != end ; ++fit) {
1686 if ((*fit)->name() == format)
1691 case LFUN_BUFFER_CHKTEX:
1692 enable = isLatex() && !lyxrc.chktex_command.empty();
1695 case LFUN_BUILD_PROGRAM:
1696 enable = isExportable("program");
1699 case LFUN_BRANCH_ACTIVATE:
1700 case LFUN_BRANCH_DEACTIVATE: {
1701 BranchList const & branchList = params().branchlist();
1702 docstring const branchName = cmd.argument();
1703 enable = !branchName.empty() && branchList.find(branchName);
1707 case LFUN_BRANCH_ADD:
1708 case LFUN_BRANCHES_RENAME:
1709 case LFUN_BUFFER_PRINT:
1710 // if no Buffer is present, then of course we won't be called!
1713 case LFUN_BUFFER_LANGUAGE:
1714 enable = !isReadonly();
1720 flag.setEnabled(enable);
1725 void Buffer::dispatch(string const & command, DispatchResult & result)
1727 return dispatch(lyxaction.lookupFunc(command), result);
1731 // NOTE We can end up here even if we have no GUI, because we are called
1732 // by LyX::exec to handled command-line requests. So we may need to check
1733 // whether we have a GUI or not. The boolean use_gui holds this information.
1734 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1737 // FIXME? if there is an Buffer LFUN that can be dispatched even
1738 // if internal, put a switch '(cmd.action)' here.
1739 dr.dispatched(false);
1742 string const argument = to_utf8(func.argument());
1743 // We'll set this back to false if need be.
1744 bool dispatched = true;
1745 undo().beginUndoGroup();
1747 switch (func.action) {
1748 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1749 if (lyxvc().inUse())
1750 lyxvc().toggleReadOnly();
1752 setReadonly(!isReadonly());
1755 case LFUN_BUFFER_EXPORT: {
1756 if (argument == "custom") {
1757 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
1760 doExport(argument, false);
1761 bool success = doExport(argument, false);
1762 dr.setError(success);
1764 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1769 case LFUN_BUFFER_UPDATE: {
1770 string format = argument;
1771 if (argument.empty())
1772 format = getDefaultOutputFormat();
1773 doExport(format, true);
1777 case LFUN_BUFFER_VIEW: {
1778 string format = argument;
1779 if (argument.empty())
1780 format = getDefaultOutputFormat();
1785 case LFUN_MASTER_BUFFER_UPDATE: {
1786 string format = argument;
1787 if (argument.empty())
1788 format = masterBuffer()->getDefaultOutputFormat();
1789 masterBuffer()->doExport(format, true);
1793 case LFUN_MASTER_BUFFER_VIEW: {
1794 string format = argument;
1795 if (argument.empty())
1796 format = masterBuffer()->getDefaultOutputFormat();
1797 masterBuffer()->preview(format);
1801 case LFUN_BUILD_PROGRAM:
1802 doExport("program", true);
1805 case LFUN_BUFFER_CHKTEX:
1809 case LFUN_BUFFER_EXPORT_CUSTOM: {
1811 string command = split(argument, format_name, ' ');
1812 Format const * format = formats.getFormat(format_name);
1814 lyxerr << "Format \"" << format_name
1815 << "\" not recognized!"
1820 // The name of the file created by the conversion process
1823 // Output to filename
1824 if (format->name() == "lyx") {
1825 string const latexname = latexName(false);
1826 filename = changeExtension(latexname,
1827 format->extension());
1828 filename = addName(temppath(), filename);
1830 if (!writeFile(FileName(filename)))
1834 doExport(format_name, true, filename);
1837 // Substitute $$FName for filename
1838 if (!contains(command, "$$FName"))
1839 command = "( " + command + " ) < $$FName";
1840 command = subst(command, "$$FName", filename);
1842 // Execute the command in the background
1844 call.startscript(Systemcall::DontWait, command);
1848 // FIXME: There is need for a command-line import.
1850 case LFUN_BUFFER_IMPORT:
1855 case LFUN_BUFFER_AUTO_SAVE:
1859 case LFUN_BRANCH_ADD: {
1860 BranchList & branchList = params().branchlist();
1861 docstring const branchName = func.argument();
1862 if (branchName.empty()) {
1866 Branch * branch = branchList.find(branchName);
1868 LYXERR0("Branch " << branchName << " does already exist.");
1870 docstring const msg =
1871 bformat(_("Branch \"%1$s\" does already exist."), branchName);
1874 branchList.add(branchName);
1876 dr.update(Update::Force);
1881 case LFUN_BRANCH_ACTIVATE:
1882 case LFUN_BRANCH_DEACTIVATE: {
1883 BranchList & branchList = params().branchlist();
1884 docstring const branchName = func.argument();
1885 // the case without a branch name is handled elsewhere
1886 if (branchName.empty()) {
1890 Branch * branch = branchList.find(branchName);
1892 LYXERR0("Branch " << branchName << " does not exist.");
1894 docstring const msg =
1895 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1898 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1900 dr.update(Update::Force);
1905 case LFUN_BRANCHES_RENAME: {
1906 if (func.argument().empty())
1909 docstring const oldname = from_utf8(func.getArg(0));
1910 docstring const newname = from_utf8(func.getArg(1));
1911 InsetIterator it = inset_iterator_begin(inset());
1912 InsetIterator const end = inset_iterator_end(inset());
1913 bool success = false;
1914 for (; it != end; ++it) {
1915 if (it->lyxCode() == BRANCH_CODE) {
1916 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1917 if (ins.branch() == oldname) {
1918 undo().recordUndo(it);
1919 ins.rename(newname);
1924 if (it->lyxCode() == INCLUDE_CODE) {
1925 // get buffer of external file
1926 InsetInclude const & ins =
1927 static_cast<InsetInclude const &>(*it);
1928 Buffer * child = ins.getChildBuffer();
1931 child->dispatch(func, dr);
1936 dr.update(Update::Force);
1940 case LFUN_BUFFER_PRINT: {
1941 // we'll assume there's a problem until we succeed
1943 string target = func.getArg(0);
1944 string target_name = func.getArg(1);
1945 string command = func.getArg(2);
1948 || target_name.empty()
1949 || command.empty()) {
1950 LYXERR0("Unable to parse " << func.argument());
1951 docstring const msg =
1952 bformat(_("Unable to parse \"%1$s\""), func.argument());
1956 if (target != "printer" && target != "file") {
1957 LYXERR0("Unrecognized target \"" << target << '"');
1958 docstring const msg =
1959 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1964 if (!doExport("dvi", true)) {
1965 showPrintError(absFileName());
1966 dr.setMessage(_("Error exporting to DVI."));
1970 // Push directory path.
1971 string const path = temppath();
1972 // Prevent the compiler from optimizing away p
1976 // there are three cases here:
1977 // 1. we print to a file
1978 // 2. we print directly to a printer
1979 // 3. we print using a spool command (print to file first)
1982 string const dviname = changeExtension(latexName(true), "dvi");
1984 if (target == "printer") {
1985 if (!lyxrc.print_spool_command.empty()) {
1986 // case 3: print using a spool
1987 string const psname = changeExtension(dviname,".ps");
1988 command += ' ' + lyxrc.print_to_file
1991 + quoteName(dviname);
1993 string command2 = lyxrc.print_spool_command + ' ';
1994 if (target_name != "default") {
1995 command2 += lyxrc.print_spool_printerprefix
1999 command2 += quoteName(psname);
2001 // If successful, then spool command
2002 res = one.startscript(Systemcall::Wait, command);
2005 // If there's no GUI, we have to wait on this command. Otherwise,
2006 // LyX deletes the temporary directory, and with it the spooled
2007 // file, before it can be printed!!
2008 Systemcall::Starttype stype = use_gui ?
2009 Systemcall::DontWait : Systemcall::Wait;
2010 res = one.startscript(stype, command2);
2013 // case 2: print directly to a printer
2014 if (target_name != "default")
2015 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2017 Systemcall::Starttype stype = use_gui ?
2018 Systemcall::DontWait : Systemcall::Wait;
2019 res = one.startscript(stype, command + quoteName(dviname));
2023 // case 1: print to a file
2024 FileName const filename(makeAbsPath(target_name, filePath()));
2025 FileName const dvifile(makeAbsPath(dviname, path));
2026 if (filename.exists()) {
2027 docstring text = bformat(
2028 _("The file %1$s already exists.\n\n"
2029 "Do you want to overwrite that file?"),
2030 makeDisplayPath(filename.absFilename()));
2031 if (Alert::prompt(_("Overwrite file?"),
2032 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2035 command += ' ' + lyxrc.print_to_file
2036 + quoteName(filename.toFilesystemEncoding())
2038 + quoteName(dvifile.toFilesystemEncoding());
2040 Systemcall::Starttype stype = use_gui ?
2041 Systemcall::DontWait : Systemcall::Wait;
2042 res = one.startscript(stype, command);
2048 dr.setMessage(_("Error running external commands."));
2049 showPrintError(absFileName());
2054 case LFUN_BUFFER_LANGUAGE: {
2055 Language const * oldL = params().language;
2056 Language const * newL = languages.getLanguage(argument);
2057 if (!newL || oldL == newL)
2059 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2060 changeLanguage(oldL, newL);
2068 dr.dispatched(dispatched);
2069 undo().endUndoGroup();
2073 void Buffer::changeLanguage(Language const * from, Language const * to)
2075 LASSERT(from, /**/);
2078 for_each(par_iterator_begin(),
2080 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2084 bool Buffer::isMultiLingual() const
2086 ParConstIterator end = par_iterator_end();
2087 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2088 if (it->isMultiLingual(params()))
2095 DocIterator Buffer::getParFromID(int const id) const
2097 Buffer * buf = const_cast<Buffer *>(this);
2099 // John says this is called with id == -1 from undo
2100 lyxerr << "getParFromID(), id: " << id << endl;
2101 return doc_iterator_end(buf);
2104 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2105 if (it.paragraph().id() == id)
2108 return doc_iterator_end(buf);
2112 bool Buffer::hasParWithID(int const id) const
2114 return !getParFromID(id).atEnd();
2118 ParIterator Buffer::par_iterator_begin()
2120 return ParIterator(doc_iterator_begin(this));
2124 ParIterator Buffer::par_iterator_end()
2126 return ParIterator(doc_iterator_end(this));
2130 ParConstIterator Buffer::par_iterator_begin() const
2132 return ParConstIterator(doc_iterator_begin(this));
2136 ParConstIterator Buffer::par_iterator_end() const
2138 return ParConstIterator(doc_iterator_end(this));
2142 Language const * Buffer::language() const
2144 return params().language;
2148 docstring const Buffer::B_(string const & l10n) const
2150 return params().B_(l10n);
2154 bool Buffer::isClean() const
2156 return d->lyx_clean;
2160 bool Buffer::isBakClean() const
2162 return d->bak_clean;
2166 bool Buffer::isExternallyModified(CheckMethod method) const
2168 LASSERT(d->filename.exists(), /**/);
2169 // if method == timestamp, check timestamp before checksum
2170 return (method == checksum_method
2171 || d->timestamp_ != d->filename.lastModified())
2172 && d->checksum_ != d->filename.checksum();
2176 void Buffer::saveCheckSum(FileName const & file) const
2178 if (file.exists()) {
2179 d->timestamp_ = file.lastModified();
2180 d->checksum_ = file.checksum();
2182 // in the case of save to a new file.
2189 void Buffer::markClean() const
2191 if (!d->lyx_clean) {
2192 d->lyx_clean = true;
2195 // if the .lyx file has been saved, we don't need an
2197 d->bak_clean = true;
2201 void Buffer::markBakClean() const
2203 d->bak_clean = true;
2207 void Buffer::setUnnamed(bool flag)
2213 bool Buffer::isUnnamed() const
2220 /// Don't check unnamed, here: isInternal() is used in
2221 /// newBuffer(), where the unnamed flag has not been set by anyone
2222 /// yet. Also, for an internal buffer, there should be no need for
2223 /// retrieving fileName() nor for checking if it is unnamed or not.
2224 bool Buffer::isInternal() const
2226 return fileName().extension() == "internal";
2230 void Buffer::markDirty()
2233 d->lyx_clean = false;
2236 d->bak_clean = false;
2238 DepClean::iterator it = d->dep_clean.begin();
2239 DepClean::const_iterator const end = d->dep_clean.end();
2241 for (; it != end; ++it)
2246 FileName Buffer::fileName() const
2252 string Buffer::absFileName() const
2254 return d->filename.absFilename();
2258 string Buffer::filePath() const
2260 return d->filename.onlyPath().absFilename() + "/";
2264 bool Buffer::isReadonly() const
2266 return d->read_only;
2270 void Buffer::setParent(Buffer const * buffer)
2272 // Avoids recursive include.
2273 d->setParent(buffer == this ? 0 : buffer);
2278 Buffer const * Buffer::parent() const
2284 void Buffer::collectRelatives(BufferSet & bufs) const
2288 parent()->collectRelatives(bufs);
2290 // loop over children
2291 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2292 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2293 for (; it != end; ++it)
2294 bufs.insert(const_cast<Buffer *>(it->first));
2298 std::vector<Buffer const *> Buffer::allRelatives() const
2301 collectRelatives(bufs);
2302 BufferSet::iterator it = bufs.begin();
2303 std::vector<Buffer const *> ret;
2304 for (; it != bufs.end(); ++it)
2310 Buffer const * Buffer::masterBuffer() const
2312 Buffer const * const pbuf = d->parent();
2316 return pbuf->masterBuffer();
2320 bool Buffer::isChild(Buffer * child) const
2322 return d->children_positions.find(child) != d->children_positions.end();
2326 DocIterator Buffer::firstChildPosition(Buffer const * child)
2328 Impl::BufferPositionMap::iterator it;
2329 it = d->children_positions.find(child);
2330 if (it == d->children_positions.end())
2331 return DocIterator(this);
2336 std::vector<Buffer *> Buffer::getChildren() const
2338 std::vector<Buffer *> clist;
2339 // loop over children
2340 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2341 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2342 for (; it != end; ++it) {
2343 Buffer * child = const_cast<Buffer *>(it->first);
2344 clist.push_back(child);
2345 // there might be grandchildren
2346 std::vector<Buffer *> glist = child->getChildren();
2347 for (vector<Buffer *>::const_iterator git = glist.begin();
2348 git != glist.end(); ++git)
2349 clist.push_back(*git);
2355 template<typename M>
2356 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2361 typename M::iterator it = m.lower_bound(x);
2362 if (it == m.begin())
2370 MacroData const * Buffer::getBufferMacro(docstring const & name,
2371 DocIterator const & pos) const
2373 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2375 // if paragraphs have no macro context set, pos will be empty
2379 // we haven't found anything yet
2380 DocIterator bestPos = par_iterator_begin();
2381 MacroData const * bestData = 0;
2383 // find macro definitions for name
2384 Impl::NamePositionScopeMacroMap::iterator nameIt
2385 = d->macros.find(name);
2386 if (nameIt != d->macros.end()) {
2387 // find last definition in front of pos or at pos itself
2388 Impl::PositionScopeMacroMap::const_iterator it
2389 = greatest_below(nameIt->second, pos);
2390 if (it != nameIt->second.end()) {
2392 // scope ends behind pos?
2393 if (pos < it->second.first) {
2394 // Looks good, remember this. If there
2395 // is no external macro behind this,
2396 // we found the right one already.
2397 bestPos = it->first;
2398 bestData = &it->second.second;
2402 // try previous macro if there is one
2403 if (it == nameIt->second.begin())
2410 // find macros in included files
2411 Impl::PositionScopeBufferMap::const_iterator it
2412 = greatest_below(d->position_to_children, pos);
2413 if (it == d->position_to_children.end())
2414 // no children before
2418 // do we know something better (i.e. later) already?
2419 if (it->first < bestPos )
2422 // scope ends behind pos?
2423 if (pos < it->second.first) {
2424 // look for macro in external file
2425 d->macro_lock = true;
2426 MacroData const * data
2427 = it->second.second->getMacro(name, false);
2428 d->macro_lock = false;
2430 bestPos = it->first;
2436 // try previous file if there is one
2437 if (it == d->position_to_children.begin())
2442 // return the best macro we have found
2447 MacroData const * Buffer::getMacro(docstring const & name,
2448 DocIterator const & pos, bool global) const
2453 // query buffer macros
2454 MacroData const * data = getBufferMacro(name, pos);
2458 // If there is a master buffer, query that
2459 Buffer const * const pbuf = d->parent();
2461 d->macro_lock = true;
2462 MacroData const * macro = pbuf->getMacro(
2463 name, *this, false);
2464 d->macro_lock = false;
2470 data = MacroTable::globalMacros().get(name);
2479 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2481 // set scope end behind the last paragraph
2482 DocIterator scope = par_iterator_begin();
2483 scope.pit() = scope.lastpit() + 1;
2485 return getMacro(name, scope, global);
2489 MacroData const * Buffer::getMacro(docstring const & name,
2490 Buffer const & child, bool global) const
2492 // look where the child buffer is included first
2493 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2494 if (it == d->children_positions.end())
2497 // check for macros at the inclusion position
2498 return getMacro(name, it->second, global);
2502 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2504 pit_type lastpit = it.lastpit();
2506 // look for macros in each paragraph
2507 while (it.pit() <= lastpit) {
2508 Paragraph & par = it.paragraph();
2510 // iterate over the insets of the current paragraph
2511 InsetList const & insets = par.insetList();
2512 InsetList::const_iterator iit = insets.begin();
2513 InsetList::const_iterator end = insets.end();
2514 for (; iit != end; ++iit) {
2515 it.pos() = iit->pos;
2517 // is it a nested text inset?
2518 if (iit->inset->asInsetText()) {
2519 // Inset needs its own scope?
2520 InsetText const * itext = iit->inset->asInsetText();
2521 bool newScope = itext->isMacroScope();
2523 // scope which ends just behind the inset
2524 DocIterator insetScope = it;
2527 // collect macros in inset
2528 it.push_back(CursorSlice(*iit->inset));
2529 updateMacros(it, newScope ? insetScope : scope);
2534 // is it an external file?
2535 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2536 // get buffer of external file
2537 InsetInclude const & inset =
2538 static_cast<InsetInclude const &>(*iit->inset);
2539 d->macro_lock = true;
2540 Buffer * child = inset.getChildBuffer();
2541 d->macro_lock = false;
2545 // register its position, but only when it is
2546 // included first in the buffer
2547 if (d->children_positions.find(child) ==
2548 d->children_positions.end())
2549 d->children_positions[child] = it;
2551 // register child with its scope
2552 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2556 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2560 MathMacroTemplate & macroTemplate =
2561 static_cast<MathMacroTemplate &>(*iit->inset);
2562 MacroContext mc(*this, it);
2563 macroTemplate.updateToContext(mc);
2566 bool valid = macroTemplate.validMacro();
2567 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2568 // then the BufferView's cursor will be invalid in
2569 // some cases which leads to crashes.
2574 d->macros[macroTemplate.name()][it] =
2575 Impl::ScopeMacro(scope, MacroData(*this, it));
2585 void Buffer::updateMacros() const
2590 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2592 // start with empty table
2594 d->children_positions.clear();
2595 d->position_to_children.clear();
2597 // Iterate over buffer, starting with first paragraph
2598 // The scope must be bigger than any lookup DocIterator
2599 // later. For the global lookup, lastpit+1 is used, hence
2600 // we use lastpit+2 here.
2601 DocIterator it = par_iterator_begin();
2602 DocIterator outerScope = it;
2603 outerScope.pit() = outerScope.lastpit() + 2;
2604 updateMacros(it, outerScope);
2608 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2610 InsetIterator it = inset_iterator_begin(inset());
2611 InsetIterator const end = inset_iterator_end(inset());
2612 for (; it != end; ++it) {
2613 if (it->lyxCode() == BRANCH_CODE) {
2614 InsetBranch & br = static_cast<InsetBranch &>(*it);
2615 docstring const name = br.branch();
2616 if (!from_master && !params().branchlist().find(name))
2617 result.push_back(name);
2618 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2619 result.push_back(name);
2622 if (it->lyxCode() == INCLUDE_CODE) {
2623 // get buffer of external file
2624 InsetInclude const & ins =
2625 static_cast<InsetInclude const &>(*it);
2626 Buffer * child = ins.getChildBuffer();
2629 child->getUsedBranches(result, true);
2632 // remove duplicates
2637 void Buffer::updateMacroInstances() const
2639 LYXERR(Debug::MACROS, "updateMacroInstances for "
2640 << d->filename.onlyFileName());
2641 DocIterator it = doc_iterator_begin(this);
2642 DocIterator end = doc_iterator_end(this);
2643 for (; it != end; it.forwardPos()) {
2644 // look for MathData cells in InsetMathNest insets
2645 Inset * inset = it.nextInset();
2649 InsetMath * minset = inset->asInsetMath();
2653 // update macro in all cells of the InsetMathNest
2654 DocIterator::idx_type n = minset->nargs();
2655 MacroContext mc = MacroContext(*this, it);
2656 for (DocIterator::idx_type i = 0; i < n; ++i) {
2657 MathData & data = minset->cell(i);
2658 data.updateMacros(0, mc);
2664 void Buffer::listMacroNames(MacroNameSet & macros) const
2669 d->macro_lock = true;
2671 // loop over macro names
2672 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2673 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2674 for (; nameIt != nameEnd; ++nameIt)
2675 macros.insert(nameIt->first);
2677 // loop over children
2678 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2679 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2680 for (; it != end; ++it)
2681 it->first->listMacroNames(macros);
2684 Buffer const * const pbuf = d->parent();
2686 pbuf->listMacroNames(macros);
2688 d->macro_lock = false;
2692 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2694 Buffer const * const pbuf = d->parent();
2699 pbuf->listMacroNames(names);
2702 MacroNameSet::iterator it = names.begin();
2703 MacroNameSet::iterator end = names.end();
2704 for (; it != end; ++it) {
2706 MacroData const * data =
2707 pbuf->getMacro(*it, *this, false);
2709 macros.insert(data);
2711 // we cannot access the original MathMacroTemplate anymore
2712 // here to calls validate method. So we do its work here manually.
2713 // FIXME: somehow make the template accessible here.
2714 if (data->optionals() > 0)
2715 features.require("xargs");
2721 Buffer::References & Buffer::references(docstring const & label)
2724 return const_cast<Buffer *>(masterBuffer())->references(label);
2726 RefCache::iterator it = d->ref_cache_.find(label);
2727 if (it != d->ref_cache_.end())
2728 return it->second.second;
2730 static InsetLabel const * dummy_il = 0;
2731 static References const dummy_refs;
2732 it = d->ref_cache_.insert(
2733 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2734 return it->second.second;
2738 Buffer::References const & Buffer::references(docstring const & label) const
2740 return const_cast<Buffer *>(this)->references(label);
2744 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2746 masterBuffer()->d->ref_cache_[label].first = il;
2750 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2752 return masterBuffer()->d->ref_cache_[label].first;
2756 void Buffer::clearReferenceCache() const
2759 d->ref_cache_.clear();
2763 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2766 //FIXME: This does not work for child documents yet.
2767 LASSERT(code == CITE_CODE, /**/);
2768 // Check if the label 'from' appears more than once
2769 vector<docstring> labels;
2771 BiblioInfo const & keys = masterBibInfo();
2772 BiblioInfo::const_iterator bit = keys.begin();
2773 BiblioInfo::const_iterator bend = keys.end();
2775 for (; bit != bend; ++bit)
2777 labels.push_back(bit->first);
2780 if (count(labels.begin(), labels.end(), from) > 1)
2783 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2784 if (it->lyxCode() == code) {
2785 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2786 docstring const oldValue = inset.getParam(paramName);
2787 if (oldValue == from)
2788 inset.setParam(paramName, to);
2794 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2795 pit_type par_end, bool full_source) const
2797 OutputParams runparams(¶ms().encoding());
2798 runparams.nice = true;
2799 runparams.flavor = params().useXetex ?
2800 OutputParams::XETEX : OutputParams::LATEX;
2801 runparams.linelen = lyxrc.plaintext_linelen;
2802 // No side effect of file copying and image conversion
2803 runparams.dryrun = true;
2806 os << "% " << _("Preview source code") << "\n\n";
2808 d->texrow.newline();
2809 d->texrow.newline();
2811 writeDocBookSource(os, absFileName(), runparams, false);
2813 // latex or literate
2814 writeLaTeXSource(os, string(), runparams, true, true);
2816 runparams.par_begin = par_begin;
2817 runparams.par_end = par_end;
2818 if (par_begin + 1 == par_end) {
2820 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2824 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2825 convert<docstring>(par_begin),
2826 convert<docstring>(par_end - 1))
2833 // output paragraphs
2835 docbookParagraphs(text(), *this, os, runparams);
2837 // latex or literate
2838 latexParagraphs(*this, text(), os, texrow, runparams);
2843 ErrorList & Buffer::errorList(string const & type) const
2845 static ErrorList emptyErrorList;
2846 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2847 if (I == d->errorLists.end())
2848 return emptyErrorList;
2854 void Buffer::updateTocItem(std::string const & type,
2855 DocIterator const & dit) const
2858 gui_->updateTocItem(type, dit);
2862 void Buffer::structureChanged() const
2865 gui_->structureChanged();
2869 void Buffer::errors(string const & err, bool from_master) const
2872 gui_->errors(err, from_master);
2876 void Buffer::message(docstring const & msg) const
2883 void Buffer::setBusy(bool on) const
2890 void Buffer::setReadOnly(bool on) const
2893 d->wa_->setReadOnly(on);
2897 void Buffer::updateTitles() const
2900 d->wa_->updateTitles();
2904 void Buffer::resetAutosaveTimers() const
2907 gui_->resetAutosaveTimers();
2911 bool Buffer::hasGuiDelegate() const
2917 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2926 class AutoSaveBuffer : public ForkedProcess {
2929 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2930 : buffer_(buffer), fname_(fname) {}
2932 virtual boost::shared_ptr<ForkedProcess> clone() const
2934 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2939 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2940 from_utf8(fname_.absFilename())));
2941 return run(DontWait);
2945 virtual int generateChild();
2947 Buffer const & buffer_;
2952 int AutoSaveBuffer::generateChild()
2954 // tmp_ret will be located (usually) in /tmp
2955 // will that be a problem?
2956 // Note that this calls ForkedCalls::fork(), so it's
2957 // ok cross-platform.
2958 pid_t const pid = fork();
2959 // If you want to debug the autosave
2960 // you should set pid to -1, and comment out the fork.
2961 if (pid != 0 && pid != -1)
2964 // pid = -1 signifies that lyx was unable
2965 // to fork. But we will do the save
2967 bool failed = false;
2968 FileName const tmp_ret = FileName::tempName("lyxauto");
2969 if (!tmp_ret.empty()) {
2970 buffer_.writeFile(tmp_ret);
2971 // assume successful write of tmp_ret
2972 if (!tmp_ret.moveTo(fname_))
2978 // failed to write/rename tmp_ret so try writing direct
2979 if (!buffer_.writeFile(fname_)) {
2980 // It is dangerous to do this in the child,
2981 // but safe in the parent, so...
2982 if (pid == -1) // emit message signal.
2983 buffer_.message(_("Autosave failed!"));
2987 if (pid == 0) // we are the child so...
2996 FileName Buffer::getAutosaveFilename() const
2998 // if the document is unnamed try to save in the backup dir, else
2999 // in the default document path, and as a last try in the filePath,
3000 // which will most often be the temporary directory
3003 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3004 : lyxrc.backupdir_path;
3005 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3008 string const fname = "#" + d->filename.onlyFileName() + "#";
3009 return makeAbsPath(fname, fpath);
3013 void Buffer::removeAutosaveFile() const
3015 FileName const f = getAutosaveFilename();
3021 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3023 FileName const newauto = getAutosaveFilename();
3024 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3025 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3029 // Perfect target for a thread...
3030 void Buffer::autoSave() const
3032 if (isBakClean() || isReadonly()) {
3033 // We don't save now, but we'll try again later
3034 resetAutosaveTimers();
3038 // emit message signal.
3039 message(_("Autosaving current document..."));
3040 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3044 resetAutosaveTimers();
3048 string Buffer::bufferFormat() const
3050 string format = params().documentClass().outputFormat();
3051 if (format == "latex") {
3052 if (params().useXetex)
3054 if (params().encoding().package() == Encoding::japanese)
3061 string Buffer::getDefaultOutputFormat() const
3063 if (!params().defaultOutputFormat.empty()
3064 && params().defaultOutputFormat != "default")
3065 return params().defaultOutputFormat;
3066 typedef vector<Format const *> Formats;
3067 Formats formats = exportableFormats(true);
3070 || params().useXetex
3071 || params().encoding().package() == Encoding::japanese) {
3072 if (formats.empty())
3074 // return the first we find
3075 return formats.front()->name();
3077 return lyxrc.default_view_format;
3082 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3083 string & result_file) const
3085 string backend_format;
3086 OutputParams runparams(¶ms().encoding());
3087 runparams.flavor = OutputParams::LATEX;
3088 runparams.linelen = lyxrc.plaintext_linelen;
3089 vector<string> backs = backends();
3090 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3091 // Get shortest path to format
3092 Graph::EdgePath path;
3093 for (vector<string>::const_iterator it = backs.begin();
3094 it != backs.end(); ++it) {
3095 Graph::EdgePath p = theConverters().getPath(*it, format);
3096 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3097 backend_format = *it;
3102 runparams.flavor = theConverters().getFlavor(path);
3104 Alert::error(_("Couldn't export file"),
3105 bformat(_("No information for exporting the format %1$s."),
3106 formats.prettyName(format)));
3110 backend_format = format;
3111 // FIXME: Don't hardcode format names here, but use a flag
3112 if (backend_format == "pdflatex")
3113 runparams.flavor = OutputParams::PDFLATEX;
3116 string filename = latexName(false);
3117 filename = addName(temppath(), filename);
3118 filename = changeExtension(filename,
3119 formats.extension(backend_format));
3122 updateMacroInstances();
3124 // Plain text backend
3125 if (backend_format == "text")
3126 writePlaintextFile(*this, FileName(filename), runparams);
3128 else if (backend_format == "xhtml")
3129 makeLyXHTMLFile(FileName(filename), runparams);
3130 else if (backend_format == "lyx")
3131 writeFile(FileName(filename));
3133 else if (isDocBook()) {
3134 runparams.nice = !put_in_tempdir;
3135 makeDocBookFile(FileName(filename), runparams);
3138 else if (backend_format == format) {
3139 runparams.nice = true;
3140 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3142 } else if (!lyxrc.tex_allows_spaces
3143 && contains(filePath(), ' ')) {
3144 Alert::error(_("File name error"),
3145 _("The directory path to the document cannot contain spaces."));
3148 runparams.nice = false;
3149 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3153 string const error_type = (format == "program")
3154 ? "Build" : bufferFormat();
3155 ErrorList & error_list = d->errorLists[error_type];
3156 string const ext = formats.extension(format);
3157 FileName const tmp_result_file(changeExtension(filename, ext));
3158 bool const success = theConverters().convert(this, FileName(filename),
3159 tmp_result_file, FileName(absFileName()), backend_format, format,
3161 // Emit the signal to show the error list.
3162 if (format != backend_format) {
3164 // also to the children, in case of master-buffer-view
3165 std::vector<Buffer *> clist = getChildren();
3166 for (vector<Buffer *>::const_iterator cit = clist.begin();
3167 cit != clist.end(); ++cit)
3168 (*cit)->errors(error_type, true);
3173 if (put_in_tempdir) {
3174 result_file = tmp_result_file.absFilename();
3178 result_file = changeExtension(exportFileName().absFilename(), ext);
3179 // We need to copy referenced files (e. g. included graphics
3180 // if format == "dvi") to the result dir.
3181 vector<ExportedFile> const files =
3182 runparams.exportdata->externalFiles(format);
3183 string const dest = onlyPath(result_file);
3184 CopyStatus status = SUCCESS;
3185 for (vector<ExportedFile>::const_iterator it = files.begin();
3186 it != files.end() && status != CANCEL; ++it) {
3187 string const fmt = formats.getFormatFromFile(it->sourceName);
3188 status = copyFile(fmt, it->sourceName,
3189 makeAbsPath(it->exportName, dest),
3190 it->exportName, status == FORCE);
3192 if (status == CANCEL) {
3193 message(_("Document export cancelled."));
3194 } else if (tmp_result_file.exists()) {
3195 // Finally copy the main file
3196 status = copyFile(format, tmp_result_file,
3197 FileName(result_file), result_file,
3199 message(bformat(_("Document exported as %1$s "
3201 formats.prettyName(format),
3202 makeDisplayPath(result_file)));
3204 // This must be a dummy converter like fax (bug 1888)
3205 message(bformat(_("Document exported as %1$s"),
3206 formats.prettyName(format)));
3213 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3216 return doExport(format, put_in_tempdir, result_file);
3220 bool Buffer::preview(string const & format) const
3223 if (!doExport(format, true, result_file))
3225 return formats.view(*this, FileName(result_file), format);
3229 bool Buffer::isExportable(string const & format) const
3231 vector<string> backs = backends();
3232 for (vector<string>::const_iterator it = backs.begin();
3233 it != backs.end(); ++it)
3234 if (theConverters().isReachable(*it, format))
3240 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3242 vector<string> backs = backends();
3243 vector<Format const *> result =
3244 theConverters().getReachable(backs[0], only_viewable, true);
3245 for (vector<string>::const_iterator it = backs.begin() + 1;
3246 it != backs.end(); ++it) {
3247 vector<Format const *> r =
3248 theConverters().getReachable(*it, only_viewable, false);
3249 result.insert(result.end(), r.begin(), r.end());
3255 vector<string> Buffer::backends() const
3258 if (params().baseClass()->isTeXClassAvailable()) {
3259 v.push_back(bufferFormat());
3260 // FIXME: Don't hardcode format names here, but use a flag
3261 if (v.back() == "latex")
3262 v.push_back("pdflatex");
3264 v.push_back("text");
3265 v.push_back("xhtml");
3271 bool Buffer::readFileHelper(FileName const & s)
3273 // File information about normal file
3275 docstring const file = makeDisplayPath(s.absFilename(), 50);
3276 docstring text = bformat(_("The specified document\n%1$s"
3277 "\ncould not be read."), file);
3278 Alert::error(_("Could not read document"), text);
3282 // Check if emergency save file exists and is newer.
3283 FileName const e(s.absFilename() + ".emergency");
3285 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3286 docstring const file = makeDisplayPath(s.absFilename(), 20);
3287 docstring const text =
3288 bformat(_("An emergency save of the document "
3290 "Recover emergency save?"), file);
3291 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3292 _("&Recover"), _("&Load Original"),
3296 // the file is not saved if we load the emergency file.
3301 if ((res = readFile(e)) == success)
3302 str = _("Document was successfully recovered.");
3304 str = _("Document was NOT successfully recovered.");
3305 str += "\n\n" + _("Remove emergency file now?") +
3306 "\n(" + from_utf8(e.absFilename())+")";
3308 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3309 _("&Remove"), _("&Keep it"))) {
3312 Alert::warning(_("Emergency file deleted"),
3313 _("Do not forget to save your file now!"), true);
3318 if (!Alert::prompt(_("Delete emergency file?"),
3319 _("Remove emergency file now?"), 1, 1,
3320 _("&Remove"), _("&Keep it")))
3328 // Now check if autosave file is newer.
3329 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3331 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3332 docstring const file = makeDisplayPath(s.absFilename(), 20);
3333 docstring const text =
3334 bformat(_("The backup of the document "
3335 "%1$s is newer.\n\nLoad the "
3336 "backup instead?"), file);
3337 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3338 _("&Load backup"), _("Load &original"),
3342 // the file is not saved if we load the autosave file.
3346 // Here we delete the autosave
3357 bool Buffer::loadLyXFile(FileName const & s)
3359 if (s.isReadableFile()) {
3360 if (readFileHelper(s)) {
3361 lyxvc().file_found_hook(s);
3362 if (!s.isWritable())
3367 docstring const file = makeDisplayPath(s.absFilename(), 20);
3368 // Here we probably should run
3369 if (LyXVC::file_not_found_hook(s)) {
3370 docstring const text =
3371 bformat(_("Do you want to retrieve the document"
3372 " %1$s from version control?"), file);
3373 int const ret = Alert::prompt(_("Retrieve from version control?"),
3374 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3377 // How can we know _how_ to do the checkout?
3378 // With the current VC support it has to be,
3379 // a RCS file since CVS do not have special ,v files.
3381 return loadLyXFile(s);
3389 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3391 TeXErrors::Errors::const_iterator cit = terr.begin();
3392 TeXErrors::Errors::const_iterator end = terr.end();
3394 for (; cit != end; ++cit) {
3397 int errorRow = cit->error_in_line;
3398 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3404 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3405 } while (found && id_start == id_end && pos_start == pos_end);
3407 errorList.push_back(ErrorItem(cit->error_desc,
3408 cit->error_text, id_start, pos_start, pos_end));
3413 void Buffer::setBuffersForInsets() const
3415 inset().setBuffer(const_cast<Buffer &>(*this));
3419 void Buffer::updateLabels(UpdateScope scope) const
3421 // Use the master text class also for child documents
3422 Buffer const * const master = masterBuffer();
3423 DocumentClass const & textclass = master->params().documentClass();
3425 // keep the buffers to be children in this set. If the call from the
3426 // master comes back we can see which of them were actually seen (i.e.
3427 // via an InsetInclude). The remaining ones in the set need still be updated.
3428 static std::set<Buffer const *> bufToUpdate;
3429 if (scope == UpdateMaster) {
3430 // If this is a child document start with the master
3431 if (master != this) {
3432 bufToUpdate.insert(this);
3433 master->updateLabels();
3434 // Do this here in case the master has no gui associated with it. Then,
3435 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3439 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3440 if (bufToUpdate.find(this) == bufToUpdate.end())
3444 // start over the counters in the master
3445 textclass.counters().reset();
3448 // update will be done below for this buffer
3449 bufToUpdate.erase(this);
3451 // update all caches
3452 clearReferenceCache();
3455 Buffer & cbuf = const_cast<Buffer &>(*this);
3457 LASSERT(!text().paragraphs().empty(), /**/);
3460 ParIterator parit = cbuf.par_iterator_begin();
3461 updateLabels(parit);
3464 // TocBackend update will be done later.
3467 cbuf.tocBackend().update();
3468 if (scope == UpdateMaster)
3469 cbuf.structureChanged();
3473 static depth_type getDepth(DocIterator const & it)
3475 depth_type depth = 0;
3476 for (size_t i = 0 ; i < it.depth() ; ++i)
3477 if (!it[i].inset().inMathed())
3478 depth += it[i].paragraph().getDepth() + 1;
3479 // remove 1 since the outer inset does not count
3483 static depth_type getItemDepth(ParIterator const & it)
3485 Paragraph const & par = *it;
3486 LabelType const labeltype = par.layout().labeltype;
3488 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3491 // this will hold the lowest depth encountered up to now.
3492 depth_type min_depth = getDepth(it);
3493 ParIterator prev_it = it;
3496 --prev_it.top().pit();
3498 // start of nested inset: go to outer par
3500 if (prev_it.empty()) {
3501 // start of document: nothing to do
3506 // We search for the first paragraph with same label
3507 // that is not more deeply nested.
3508 Paragraph & prev_par = *prev_it;
3509 depth_type const prev_depth = getDepth(prev_it);
3510 if (labeltype == prev_par.layout().labeltype) {
3511 if (prev_depth < min_depth)
3512 return prev_par.itemdepth + 1;
3513 if (prev_depth == min_depth)
3514 return prev_par.itemdepth;
3516 min_depth = min(min_depth, prev_depth);
3517 // small optimization: if we are at depth 0, we won't
3518 // find anything else
3519 if (prev_depth == 0)
3525 static bool needEnumCounterReset(ParIterator const & it)
3527 Paragraph const & par = *it;
3528 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3529 depth_type const cur_depth = par.getDepth();
3530 ParIterator prev_it = it;
3531 while (prev_it.pit()) {
3532 --prev_it.top().pit();
3533 Paragraph const & prev_par = *prev_it;
3534 if (prev_par.getDepth() <= cur_depth)
3535 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3537 // start of nested inset: reset
3542 // set the label of a paragraph. This includes the counters.
3543 static void setLabel(Buffer const & buf, ParIterator & it)
3545 BufferParams const & bp = buf.masterBuffer()->params();
3546 DocumentClass const & textclass = bp.documentClass();
3547 Paragraph & par = it.paragraph();
3548 Layout const & layout = par.layout();
3549 Counters & counters = textclass.counters();
3551 if (par.params().startOfAppendix()) {
3552 // FIXME: only the counter corresponding to toplevel
3553 // sectionning should be reset
3555 counters.appendix(true);
3557 par.params().appendix(counters.appendix());
3559 // Compute the item depth of the paragraph
3560 par.itemdepth = getItemDepth(it);
3562 if (layout.margintype == MARGIN_MANUAL
3563 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3564 if (par.params().labelWidthString().empty())
3565 par.params().labelWidthString(par.expandLabel(layout, bp));
3567 par.params().labelWidthString(docstring());
3570 switch(layout.labeltype) {
3572 if (layout.toclevel <= bp.secnumdepth
3573 && (layout.latextype != LATEX_ENVIRONMENT
3574 || it.text()->isFirstInSequence(it.pit()))) {
3575 counters.step(layout.counter);
3576 par.params().labelString(
3577 par.expandLabel(layout, bp));
3579 par.params().labelString(docstring());
3582 case LABEL_ITEMIZE: {
3583 // At some point of time we should do something more
3584 // clever here, like:
3585 // par.params().labelString(
3586 // bp.user_defined_bullet(par.itemdepth).getText());
3587 // for now, use a simple hardcoded label
3588 docstring itemlabel;
3589 switch (par.itemdepth) {
3591 itemlabel = char_type(0x2022);
3594 itemlabel = char_type(0x2013);
3597 itemlabel = char_type(0x2217);
3600 itemlabel = char_type(0x2219); // or 0x00b7
3603 par.params().labelString(itemlabel);
3607 case LABEL_ENUMERATE: {
3608 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3610 switch (par.itemdepth) {
3619 enumcounter += "iv";
3622 // not a valid enumdepth...
3626 // Maybe we have to reset the enumeration counter.
3627 if (needEnumCounterReset(it))
3628 counters.reset(enumcounter);
3629 counters.step(enumcounter);
3631 string const & lang = par.getParLanguage(bp)->code();
3632 par.params().labelString(counters.theCounter(enumcounter, lang));
3637 case LABEL_SENSITIVE: {
3638 string const & type = counters.current_float();
3639 docstring full_label;
3641 full_label = buf.B_("Senseless!!! ");
3643 docstring name = buf.B_(textclass.floats().getType(type).name());
3644 if (counters.hasCounter(from_utf8(type))) {
3645 string const & lang = par.getParLanguage(bp)->code();
3646 counters.step(from_utf8(type));
3647 full_label = bformat(from_ascii("%1$s %2$s:"),
3649 counters.theCounter(from_utf8(type), lang));
3651 full_label = bformat(from_ascii("%1$s #:"), name);
3653 par.params().labelString(full_label);
3657 case LABEL_NO_LABEL:
3658 par.params().labelString(docstring());
3662 case LABEL_TOP_ENVIRONMENT:
3663 case LABEL_CENTERED_TOP_ENVIRONMENT:
3666 par.params().labelString(par.expandLabel(layout, bp));
3672 void Buffer::updateLabels(ParIterator & parit) const
3674 LASSERT(parit.pit() == 0, /**/);
3676 // set the position of the text in the buffer to be able
3677 // to resolve macros in it. This has nothing to do with
3678 // labels, but by putting it here we avoid implementing
3679 // a whole bunch of traversal routines just for this call.
3680 parit.text()->setMacrocontextPosition(parit);
3682 depth_type maxdepth = 0;
3683 pit_type const lastpit = parit.lastpit();
3684 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3685 // reduce depth if necessary
3686 parit->params().depth(min(parit->params().depth(), maxdepth));
3687 maxdepth = parit->getMaxDepthAfter();
3689 // set the counter for this paragraph
3690 setLabel(*this, parit);
3693 InsetList::const_iterator iit = parit->insetList().begin();
3694 InsetList::const_iterator end = parit->insetList().end();
3695 for (; iit != end; ++iit) {
3696 parit.pos() = iit->pos;
3697 iit->inset->updateLabels(parit);
3703 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3704 WordLangTuple & word_lang, docstring_list & suggestions) const
3708 suggestions.clear();
3709 word_lang = WordLangTuple();
3710 // OK, we start from here.
3711 DocIterator const end = doc_iterator_end(this);
3712 for (; from != end; from.forwardPos()) {
3713 // We are only interested in text so remove the math CursorSlice.
3714 while (from.inMathed())
3715 from.forwardInset();
3717 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {