3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DocIterator.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
55 #include "TexStream.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
60 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/lassert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
110 using namespace lyx::support;
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
119 // Do not remove the comment below, so we get merge conflict in
120 // independent branches. Instead add your own.
121 int const LYX_FORMAT = 348; // uwestoehr: add support for \*phantom
123 typedef map<string, bool> DepClean;
124 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
128 class BufferSet : public std::set<Buffer const *> {};
133 Impl(Buffer & parent, FileName const & file, bool readonly);
147 mutable TexRow texrow;
149 /// need to regenerate .tex?
153 mutable bool lyx_clean;
155 /// is autosave needed?
156 mutable bool bak_clean;
158 /// is this a unnamed file (New...)?
164 /// name of the file the buffer is associated with.
167 /** Set to true only when the file is fully loaded.
168 * Used to prevent the premature generation of previews
169 * and by the citation inset.
171 bool file_fully_loaded;
174 mutable TocBackend toc_backend;
177 typedef pair<DocIterator, MacroData> ScopeMacro;
178 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
179 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
180 /// map from the macro name to the position map,
181 /// which maps the macro definition position to the scope and the MacroData.
182 NamePositionScopeMacroMap macros;
185 /// positions of child buffers in the buffer
186 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
187 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
188 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
189 /// position of children buffers in this buffer
190 BufferPositionMap children_positions;
191 /// map from children inclusion positions to their scope and their buffer
192 PositionScopeBufferMap position_to_children;
194 /// Container for all sort of Buffer dependant errors.
195 map<string, ErrorList> errorLists;
197 /// timestamp and checksum used to test if the file has been externally
198 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
200 unsigned long checksum_;
203 frontend::WorkAreaManager * wa_;
208 /// A cache for the bibfiles (including bibfiles of loaded child
209 /// documents), needed for appropriate update of natbib labels.
210 mutable support::FileNameList bibfilesCache_;
212 // FIXME The caching mechanism could be improved. At present, we have a
213 // cache for each Buffer, that caches all the bibliography info for that
214 // Buffer. A more efficient solution would be to have a global cache per
215 // file, and then to construct the Buffer's bibinfo from that.
216 /// A cache for bibliography info
217 mutable BiblioInfo bibinfo_;
218 /// whether the bibinfo cache is valid
219 bool bibinfoCacheValid_;
220 /// Cache of timestamps of .bib files
221 map<FileName, time_t> bibfileStatus_;
223 mutable RefCache ref_cache_;
225 /// our Text that should be wrapped in an InsetText
228 /// This is here to force the test to be done whenever parent_buffer
230 Buffer const * parent() const {
231 if (!theBufferList().isLoaded(parent_buffer))
233 return parent_buffer;
236 void setParent(Buffer const * pb) { parent_buffer = pb; }
238 /// So we can force access via the accessors.
239 mutable Buffer const * parent_buffer;
243 /// Creates the per buffer temporary directory
244 static FileName createBufferTmpDir()
247 // We are in our own directory. Why bother to mangle name?
248 // In fact I wrote this code to circumvent a problematic behaviour
249 // (bug?) of EMX mkstemp().
250 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
251 convert<string>(count++));
253 if (!tmpfl.createDirectory(0777)) {
254 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
255 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
256 from_utf8(tmpfl.absFilename())));
262 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
263 : lyx_clean(true), bak_clean(true), unnamed(false),
264 read_only(readonly_), filename(file), file_fully_loaded(false),
265 toc_backend(&parent), macro_lock(false), timestamp_(0),
266 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
269 temppath = createBufferTmpDir();
270 lyxvc.setBuffer(&parent);
272 wa_ = new frontend::WorkAreaManager;
276 Buffer::Buffer(string const & file, bool readonly)
277 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
279 LYXERR(Debug::INFO, "Buffer::Buffer()");
281 d->inset = new InsetText(*this);
282 d->inset->setAutoBreakRows(true);
283 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
289 LYXERR(Debug::INFO, "Buffer::~Buffer()");
290 // here the buffer should take care that it is
291 // saved properly, before it goes into the void.
293 // GuiView already destroyed
296 if (d->unnamed && d->filename.extension() == "internal") {
297 // No need to do additional cleanups for internal buffer.
302 // loop over children
303 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
304 Impl::BufferPositionMap::iterator end = d->children_positions.end();
305 for (; it != end; ++it) {
306 Buffer * child = const_cast<Buffer *>(it->first);
307 // The child buffer might have been closed already.
308 if (theBufferList().isLoaded(child))
309 theBufferList().releaseChild(this, child);
312 // clear references to children in macro tables
313 d->children_positions.clear();
314 d->position_to_children.clear();
316 if (!d->temppath.destroyDirectory()) {
317 Alert::warning(_("Could not remove temporary directory"),
318 bformat(_("Could not remove the temporary directory %1$s"),
319 from_utf8(d->temppath.absFilename())));
322 // Remove any previewed LaTeX snippets associated with this buffer.
323 thePreviews().removeLoader(*this);
329 void Buffer::changed() const
336 frontend::WorkAreaManager & Buffer::workAreaManager() const
338 LASSERT(d->wa_, /**/);
343 Text & Buffer::text() const
345 return d->inset->text();
349 Inset & Buffer::inset() const
355 BufferParams & Buffer::params()
361 BufferParams const & Buffer::params() const
367 ParagraphList & Buffer::paragraphs()
369 return text().paragraphs();
373 ParagraphList const & Buffer::paragraphs() const
375 return text().paragraphs();
379 LyXVC & Buffer::lyxvc()
385 LyXVC const & Buffer::lyxvc() const
391 string const Buffer::temppath() const
393 return d->temppath.absFilename();
397 TexRow & Buffer::texrow()
403 TexRow const & Buffer::texrow() const
409 TocBackend & Buffer::tocBackend() const
411 return d->toc_backend;
415 Undo & Buffer::undo()
421 string Buffer::latexName(bool const no_path) const
423 FileName latex_name = makeLatexName(d->filename);
424 return no_path ? latex_name.onlyFileName()
425 : latex_name.absFilename();
429 string Buffer::logName(LogType * type) const
431 string const filename = latexName(false);
433 if (filename.empty()) {
439 string const path = temppath();
441 FileName const fname(addName(temppath(),
442 onlyFilename(changeExtension(filename,
444 FileName const bname(
445 addName(path, onlyFilename(
446 changeExtension(filename,
447 formats.extension("literate") + ".out"))));
449 // If no Latex log or Build log is newer, show Build log
451 if (bname.exists() &&
452 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
453 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
456 return bname.absFilename();
458 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
461 return fname.absFilename();
465 void Buffer::setReadonly(bool const flag)
467 if (d->read_only != flag) {
474 void Buffer::setFileName(string const & newfile)
476 d->filename = makeAbsPath(newfile);
477 setReadonly(d->filename.isReadOnly());
482 int Buffer::readHeader(Lexer & lex)
484 int unknown_tokens = 0;
486 int begin_header_line = -1;
488 // Initialize parameters that may be/go lacking in header:
489 params().branchlist().clear();
490 params().preamble.erase();
491 params().options.erase();
492 params().master.erase();
493 params().float_placement.erase();
494 params().paperwidth.erase();
495 params().paperheight.erase();
496 params().leftmargin.erase();
497 params().rightmargin.erase();
498 params().topmargin.erase();
499 params().bottommargin.erase();
500 params().headheight.erase();
501 params().headsep.erase();
502 params().footskip.erase();
503 params().columnsep.erase();
504 params().fontsCJK.erase();
505 params().listings_params.clear();
506 params().clearLayoutModules();
507 params().clearRemovedModules();
508 params().pdfoptions().clear();
510 for (int i = 0; i < 4; ++i) {
511 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
512 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
515 ErrorList & errorList = d->errorLists["Parse"];
524 if (token == "\\end_header")
528 if (token == "\\begin_header") {
529 begin_header_line = line;
533 LYXERR(Debug::PARSER, "Handling document header token: `"
536 string unknown = params().readToken(lex, token, d->filename.onlyPath());
537 if (!unknown.empty()) {
538 if (unknown[0] != '\\' && token == "\\textclass") {
539 Alert::warning(_("Unknown document class"),
540 bformat(_("Using the default document class, because the "
541 "class %1$s is unknown."), from_utf8(unknown)));
544 docstring const s = bformat(_("Unknown token: "
548 errorList.push_back(ErrorItem(_("Document header error"),
553 if (begin_header_line) {
554 docstring const s = _("\\begin_header is missing");
555 errorList.push_back(ErrorItem(_("Document header error"),
559 params().makeDocumentClass();
561 return unknown_tokens;
566 // changed to be public and have one parameter
567 // Returns true if "\end_document" is not read (Asger)
568 bool Buffer::readDocument(Lexer & lex)
570 ErrorList & errorList = d->errorLists["Parse"];
573 if (!lex.checkFor("\\begin_document")) {
574 docstring const s = _("\\begin_document is missing");
575 errorList.push_back(ErrorItem(_("Document header error"),
579 // we are reading in a brand new document
580 LASSERT(paragraphs().empty(), /**/);
584 if (params().outputChanges) {
585 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
586 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
587 LaTeXFeatures::isAvailable("xcolor");
589 if (!dvipost && !xcolorulem) {
590 Alert::warning(_("Changes not shown in LaTeX output"),
591 _("Changes will not be highlighted in LaTeX output, "
592 "because neither dvipost nor xcolor/ulem are installed.\n"
593 "Please install these packages or redefine "
594 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
595 } else if (!xcolorulem) {
596 Alert::warning(_("Changes not shown in LaTeX output"),
597 _("Changes will not be highlighted in LaTeX output "
598 "when using pdflatex, because xcolor and ulem are not installed.\n"
599 "Please install both packages or redefine "
600 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
604 if (!params().master.empty()) {
605 FileName const master_file = makeAbsPath(params().master,
606 onlyPath(absFileName()));
607 if (isLyXFilename(master_file.absFilename())) {
609 checkAndLoadLyXFile(master_file, true);
611 // necessary e.g. after a reload
612 // to re-register the child (bug 5873)
613 // FIXME: clean up updateMacros (here, only
614 // child registering is needed).
615 master->updateMacros();
616 // set master as master buffer, but only
617 // if we are a real child
618 if (master->isChild(this))
620 // if the master is not fully loaded
621 // it is probably just loading this
622 // child. No warning needed then.
623 else if (master->isFullyLoaded())
624 LYXERR0("The master '"
626 << "' assigned to this document ("
628 << ") does not include "
629 "this document. Ignoring the master assignment.");
635 bool const res = text().read(*this, lex, errorList, d->inset);
638 updateMacroInstances();
643 // needed to insert the selection
644 void Buffer::insertStringAsLines(ParagraphList & pars,
645 pit_type & pit, pos_type & pos,
646 Font const & fn, docstring const & str, bool autobreakrows)
650 // insert the string, don't insert doublespace
651 bool space_inserted = true;
652 for (docstring::const_iterator cit = str.begin();
653 cit != str.end(); ++cit) {
654 Paragraph & par = pars[pit];
656 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
657 breakParagraph(params(), pars, pit, pos,
658 par.layout().isEnvironment());
661 space_inserted = true;
665 // do not insert consecutive spaces if !free_spacing
666 } else if ((*cit == ' ' || *cit == '\t') &&
667 space_inserted && !par.isFreeSpacing()) {
669 } else if (*cit == '\t') {
670 if (!par.isFreeSpacing()) {
671 // tabs are like spaces here
672 par.insertChar(pos, ' ', font, params().trackChanges);
674 space_inserted = true;
676 par.insertChar(pos, *cit, font, params().trackChanges);
678 space_inserted = true;
680 } else if (!isPrintable(*cit)) {
681 // Ignore unprintables
684 // just insert the character
685 par.insertChar(pos, *cit, font, params().trackChanges);
687 space_inserted = (*cit == ' ');
694 bool Buffer::readString(string const & s)
696 params().compressed = false;
698 // remove dummy empty par
699 paragraphs().clear();
703 FileName const name = FileName::tempName("Buffer_readString");
704 switch (readFile(lex, name, true)) {
708 // We need to call lyx2lyx, so write the input to a file
709 ofstream os(name.toFilesystemEncoding().c_str());
712 return readFile(name);
722 bool Buffer::readFile(FileName const & filename)
724 FileName fname(filename);
726 params().compressed = fname.isZippedFile();
728 // remove dummy empty par
729 paragraphs().clear();
732 if (readFile(lex, fname) != success)
739 bool Buffer::isFullyLoaded() const
741 return d->file_fully_loaded;
745 void Buffer::setFullyLoaded(bool value)
747 d->file_fully_loaded = value;
751 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
754 LASSERT(!filename.empty(), /**/);
756 // the first (non-comment) token _must_ be...
757 if (!lex.checkFor("\\lyxformat")) {
758 Alert::error(_("Document format failure"),
759 bformat(_("%1$s is not a readable LyX document."),
760 from_utf8(filename.absFilename())));
766 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
767 // if present remove ".," from string.
768 size_t dot = tmp_format.find_first_of(".,");
769 //lyxerr << " dot found at " << dot << endl;
770 if (dot != string::npos)
771 tmp_format.erase(dot, 1);
772 int const file_format = convert<int>(tmp_format);
773 //lyxerr << "format: " << file_format << endl;
775 // save timestamp and checksum of the original disk file, making sure
776 // to not overwrite them with those of the file created in the tempdir
777 // when it has to be converted to the current format.
779 // Save the timestamp and checksum of disk file. If filename is an
780 // emergency file, save the timestamp and checksum of the original lyx file
781 // because isExternallyModified will check for this file. (BUG4193)
782 string diskfile = filename.absFilename();
783 if (suffixIs(diskfile, ".emergency"))
784 diskfile = diskfile.substr(0, diskfile.size() - 10);
785 saveCheckSum(FileName(diskfile));
788 if (file_format != LYX_FORMAT) {
791 // lyx2lyx would fail
794 FileName const tmpfile = FileName::tempName("Buffer_readFile");
795 if (tmpfile.empty()) {
796 Alert::error(_("Conversion failed"),
797 bformat(_("%1$s is from a different"
798 " version of LyX, but a temporary"
799 " file for converting it could"
801 from_utf8(filename.absFilename())));
804 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
805 if (lyx2lyx.empty()) {
806 Alert::error(_("Conversion script not found"),
807 bformat(_("%1$s is from a different"
808 " version of LyX, but the"
809 " conversion script lyx2lyx"
810 " could not be found."),
811 from_utf8(filename.absFilename())));
814 ostringstream command;
815 command << os::python()
816 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
817 << " -t " << convert<string>(LYX_FORMAT)
818 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
819 << ' ' << quoteName(filename.toFilesystemEncoding());
820 string const command_str = command.str();
822 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
824 cmd_ret const ret = runCommand(command_str);
825 if (ret.first != 0) {
826 Alert::error(_("Conversion script failed"),
827 bformat(_("%1$s is from a different version"
828 " of LyX, but the lyx2lyx script"
829 " failed to convert it."),
830 from_utf8(filename.absFilename())));
833 bool const ret = readFile(tmpfile);
834 // Do stuff with tmpfile name and buffer name here.
835 return ret ? success : failure;
840 if (readDocument(lex)) {
841 Alert::error(_("Document format failure"),
842 bformat(_("%1$s ended unexpectedly, which means"
843 " that it is probably corrupted."),
844 from_utf8(filename.absFilename())));
847 d->file_fully_loaded = true;
852 // Should probably be moved to somewhere else: BufferView? LyXView?
853 bool Buffer::save() const
855 // We don't need autosaves in the immediate future. (Asger)
856 resetAutosaveTimers();
858 string const encodedFilename = d->filename.toFilesystemEncoding();
861 bool madeBackup = false;
863 // make a backup if the file already exists
864 if (lyxrc.make_backup && fileName().exists()) {
865 backupName = FileName(absFileName() + '~');
866 if (!lyxrc.backupdir_path.empty()) {
867 string const mangledName =
868 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
869 backupName = FileName(addName(lyxrc.backupdir_path,
872 if (fileName().copyTo(backupName)) {
875 Alert::error(_("Backup failure"),
876 bformat(_("Cannot create backup file %1$s.\n"
877 "Please check whether the directory exists and is writeable."),
878 from_utf8(backupName.absFilename())));
879 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
883 // ask if the disk file has been externally modified (use checksum method)
884 if (fileName().exists() && isExternallyModified(checksum_method)) {
885 docstring const file = makeDisplayPath(absFileName(), 20);
886 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
887 "you want to overwrite this file?"), file);
888 int const ret = Alert::prompt(_("Overwrite modified file?"),
889 text, 1, 1, _("&Overwrite"), _("&Cancel"));
894 if (writeFile(d->filename)) {
898 // Saving failed, so backup is not backup
900 backupName.moveTo(d->filename);
906 bool Buffer::writeFile(FileName const & fname) const
908 if (d->read_only && fname == d->filename)
913 docstring const str = bformat(_("Saving document %1$s..."),
914 makeDisplayPath(fname.absFilename()));
917 if (params().compressed) {
918 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
919 retval = ofs && write(ofs);
921 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
922 retval = ofs && write(ofs);
926 message(str + _(" could not write file!"));
930 removeAutosaveFile(d->filename.absFilename());
932 saveCheckSum(d->filename);
933 message(str + _(" done."));
939 bool Buffer::write(ostream & ofs) const
942 // Use the standard "C" locale for file output.
943 ofs.imbue(locale::classic());
946 // The top of the file should not be written by params().
948 // write out a comment in the top of the file
949 ofs << "#LyX " << lyx_version
950 << " created this file. For more info see http://www.lyx.org/\n"
951 << "\\lyxformat " << LYX_FORMAT << "\n"
952 << "\\begin_document\n";
954 /// For each author, set 'used' to true if there is a change
955 /// by this author in the document; otherwise set it to 'false'.
956 AuthorList::Authors::const_iterator a_it = params().authors().begin();
957 AuthorList::Authors::const_iterator a_end = params().authors().end();
958 for (; a_it != a_end; ++a_it)
959 a_it->second.setUsed(false);
961 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
962 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
963 for ( ; it != end; ++it)
964 it->checkAuthors(params().authors());
966 // now write out the buffer parameters.
967 ofs << "\\begin_header\n";
968 params().writeFile(ofs);
969 ofs << "\\end_header\n";
972 ofs << "\n\\begin_body\n";
973 text().write(*this, ofs);
974 ofs << "\n\\end_body\n";
976 // Write marker that shows file is complete
977 ofs << "\\end_document" << endl;
979 // Shouldn't really be needed....
982 // how to check if close went ok?
983 // Following is an attempt... (BE 20001011)
985 // good() returns false if any error occured, including some
987 // bad() returns true if something bad happened in the buffer,
988 // which should include file system full errors.
993 lyxerr << "File was not closed properly." << endl;
1000 bool Buffer::makeLaTeXFile(FileName const & fname,
1001 string const & original_path,
1002 OutputParams const & runparams,
1003 bool output_preamble, bool output_body) const
1005 string const encoding = runparams.encoding->iconvName();
1006 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1009 try { ofs.reset(encoding); }
1010 catch (iconv_codecvt_facet_exception & e) {
1011 lyxerr << "Caught iconv exception: " << e.what() << endl;
1012 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1013 "verify that the support software for your encoding (%1$s) is "
1014 "properly installed"), from_ascii(encoding)));
1017 if (!openFileWrite(ofs, fname))
1020 //TexStream ts(ofs.rdbuf(), &texrow());
1021 ErrorList & errorList = d->errorLists["Export"];
1023 bool failed_export = false;
1026 writeLaTeXSource(ofs, original_path,
1027 runparams, output_preamble, output_body);
1029 catch (EncodingException & e) {
1030 odocstringstream ods;
1031 ods.put(e.failed_char);
1033 oss << "0x" << hex << e.failed_char << dec;
1034 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1035 " (code point %2$s)"),
1036 ods.str(), from_utf8(oss.str()));
1037 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1038 "representable in the chosen encoding.\n"
1039 "Changing the document encoding to utf8 could help."),
1040 e.par_id, e.pos, e.pos + 1));
1041 failed_export = true;
1043 catch (iconv_codecvt_facet_exception & e) {
1044 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1045 _(e.what()), -1, 0, 0));
1046 failed_export = true;
1048 catch (exception const & e) {
1049 errorList.push_back(ErrorItem(_("conversion failed"),
1050 _(e.what()), -1, 0, 0));
1051 failed_export = true;
1054 lyxerr << "Caught some really weird exception..." << endl;
1060 failed_export = true;
1061 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1065 return !failed_export;
1069 void Buffer::writeLaTeXSource(odocstream & os,
1070 string const & original_path,
1071 OutputParams const & runparams_in,
1072 bool const output_preamble, bool const output_body) const
1074 // The child documents, if any, shall be already loaded at this point.
1076 OutputParams runparams = runparams_in;
1078 // Classify the unicode characters appearing in math insets
1079 Encodings::initUnicodeMath(*this);
1081 // validate the buffer.
1082 LYXERR(Debug::LATEX, " Validating buffer...");
1083 LaTeXFeatures features(*this, params(), runparams);
1085 LYXERR(Debug::LATEX, " Buffer validation done.");
1087 // The starting paragraph of the coming rows is the
1088 // first paragraph of the document. (Asger)
1089 if (output_preamble && runparams.nice) {
1090 os << "%% LyX " << lyx_version << " created this file. "
1091 "For more info, see http://www.lyx.org/.\n"
1092 "%% Do not edit unless you really know what "
1094 d->texrow.newline();
1095 d->texrow.newline();
1097 LYXERR(Debug::INFO, "lyx document header finished");
1099 // Don't move this behind the parent_buffer=0 code below,
1100 // because then the macros will not get the right "redefinition"
1101 // flag as they don't see the parent macros which are output before.
1104 // fold macros if possible, still with parent buffer as the
1105 // macros will be put in the prefix anyway.
1106 updateMacroInstances();
1108 // There are a few differences between nice LaTeX and usual files:
1109 // usual is \batchmode and has a
1110 // special input@path to allow the including of figures
1111 // with either \input or \includegraphics (what figinsets do).
1112 // input@path is set when the actual parameter
1113 // original_path is set. This is done for usual tex-file, but not
1114 // for nice-latex-file. (Matthias 250696)
1115 // Note that input@path is only needed for something the user does
1116 // in the preamble, included .tex files or ERT, files included by
1117 // LyX work without it.
1118 if (output_preamble) {
1119 if (!runparams.nice) {
1120 // code for usual, NOT nice-latex-file
1121 os << "\\batchmode\n"; // changed
1122 // from \nonstopmode
1123 d->texrow.newline();
1125 if (!original_path.empty()) {
1127 // We don't know the encoding of inputpath
1128 docstring const inputpath = from_utf8(latex_path(original_path));
1129 os << "\\makeatletter\n"
1130 << "\\def\\input@path{{"
1131 << inputpath << "/}}\n"
1132 << "\\makeatother\n";
1133 d->texrow.newline();
1134 d->texrow.newline();
1135 d->texrow.newline();
1138 // get parent macros (if this buffer has a parent) which will be
1139 // written at the document begin further down.
1140 MacroSet parentMacros;
1141 listParentMacros(parentMacros, features);
1143 // Write the preamble
1144 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1146 runparams.use_japanese = features.isRequired("japanese");
1152 os << "\\begin{document}\n";
1153 d->texrow.newline();
1155 // output the parent macros
1156 MacroSet::iterator it = parentMacros.begin();
1157 MacroSet::iterator end = parentMacros.end();
1158 for (; it != end; ++it)
1159 (*it)->write(os, true);
1160 } // output_preamble
1162 d->texrow.start(paragraphs().begin()->id(), 0);
1164 LYXERR(Debug::INFO, "preamble finished, now the body.");
1166 // if we are doing a real file with body, even if this is the
1167 // child of some other buffer, let's cut the link here.
1168 // This happens for example if only a child document is printed.
1169 Buffer const * save_parent = 0;
1170 if (output_preamble) {
1171 save_parent = d->parent();
1176 latexParagraphs(*this, text(), os, d->texrow, runparams);
1178 // Restore the parenthood if needed
1179 if (output_preamble)
1180 d->setParent(save_parent);
1182 // add this just in case after all the paragraphs
1184 d->texrow.newline();
1186 if (output_preamble) {
1187 os << "\\end{document}\n";
1188 d->texrow.newline();
1189 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1191 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1193 runparams_in.encoding = runparams.encoding;
1195 // Just to be sure. (Asger)
1196 d->texrow.newline();
1198 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1199 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1203 bool Buffer::isLatex() const
1205 return params().documentClass().outputType() == LATEX;
1209 bool Buffer::isLiterate() const
1211 return params().documentClass().outputType() == LITERATE;
1215 bool Buffer::isDocBook() const
1217 return params().documentClass().outputType() == DOCBOOK;
1221 void Buffer::makeDocBookFile(FileName const & fname,
1222 OutputParams const & runparams,
1223 bool const body_only) const
1225 LYXERR(Debug::LATEX, "makeDocBookFile...");
1228 if (!openFileWrite(ofs, fname))
1231 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1235 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1239 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1240 OutputParams const & runparams,
1241 bool const only_body) const
1243 LaTeXFeatures features(*this, params(), runparams);
1248 DocumentClass const & tclass = params().documentClass();
1249 string const top_element = tclass.latexname();
1252 if (runparams.flavor == OutputParams::XML)
1253 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1256 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1259 if (! tclass.class_header().empty())
1260 os << from_ascii(tclass.class_header());
1261 else if (runparams.flavor == OutputParams::XML)
1262 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1263 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1265 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1267 docstring preamble = from_utf8(params().preamble);
1268 if (runparams.flavor != OutputParams::XML ) {
1269 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1270 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1271 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1272 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1275 string const name = runparams.nice
1276 ? changeExtension(absFileName(), ".sgml") : fname;
1277 preamble += features.getIncludedFiles(name);
1278 preamble += features.getLyXSGMLEntities();
1280 if (!preamble.empty()) {
1281 os << "\n [ " << preamble << " ]";
1286 string top = top_element;
1288 if (runparams.flavor == OutputParams::XML)
1289 top += params().language->code();
1291 top += params().language->code().substr(0, 2);
1294 if (!params().options.empty()) {
1296 top += params().options;
1299 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1300 << " file was created by LyX " << lyx_version
1301 << "\n See http://www.lyx.org/ for more information -->\n";
1303 params().documentClass().counters().reset();
1307 sgml::openTag(os, top);
1309 docbookParagraphs(paragraphs(), *this, os, runparams);
1310 sgml::closeTag(os, top_element);
1314 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1315 // Other flags: -wall -v0 -x
1316 int Buffer::runChktex()
1320 // get LaTeX-Filename
1321 FileName const path(temppath());
1322 string const name = addName(path.absFilename(), latexName());
1323 string const org_path = filePath();
1325 PathChanger p(path); // path to LaTeX file
1326 message(_("Running chktex..."));
1328 // Generate the LaTeX file if neccessary
1329 OutputParams runparams(¶ms().encoding());
1330 runparams.flavor = OutputParams::LATEX;
1331 runparams.nice = false;
1332 makeLaTeXFile(FileName(name), org_path, runparams);
1335 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1336 int const res = chktex.run(terr); // run chktex
1339 Alert::error(_("chktex failure"),
1340 _("Could not run chktex successfully."));
1341 } else if (res > 0) {
1342 ErrorList & errlist = d->errorLists["ChkTeX"];
1344 bufferErrors(terr, errlist);
1355 void Buffer::validate(LaTeXFeatures & features) const
1357 params().validate(features);
1361 for_each(paragraphs().begin(), paragraphs().end(),
1362 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1364 if (lyxerr.debugging(Debug::LATEX)) {
1365 features.showStruct();
1370 void Buffer::getLabelList(vector<docstring> & list) const
1372 // If this is a child document, use the parent's list instead.
1373 Buffer const * const pbuf = d->parent();
1375 pbuf->getLabelList(list);
1380 Toc & toc = d->toc_backend.toc("label");
1381 TocIterator toc_it = toc.begin();
1382 TocIterator end = toc.end();
1383 for (; toc_it != end; ++toc_it) {
1384 if (toc_it->depth() == 0)
1385 list.push_back(toc_it->str());
1390 void Buffer::updateBibfilesCache(UpdateScope scope) const
1392 // If this is a child document, use the parent's cache instead.
1393 Buffer const * const pbuf = d->parent();
1394 if (pbuf && scope != UpdateChildOnly) {
1395 pbuf->updateBibfilesCache();
1399 d->bibfilesCache_.clear();
1400 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1401 if (it->lyxCode() == BIBTEX_CODE) {
1402 InsetBibtex const & inset =
1403 static_cast<InsetBibtex const &>(*it);
1404 support::FileNameList const bibfiles = inset.getBibFiles();
1405 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1408 } else if (it->lyxCode() == INCLUDE_CODE) {
1409 InsetInclude & inset =
1410 static_cast<InsetInclude &>(*it);
1411 inset.updateBibfilesCache();
1412 support::FileNameList const & bibfiles =
1413 inset.getBibfilesCache();
1414 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1419 // the bibinfo cache is now invalid
1420 d->bibinfoCacheValid_ = false;
1424 void Buffer::invalidateBibinfoCache()
1426 d->bibinfoCacheValid_ = false;
1430 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1432 // If this is a child document, use the parent's cache instead.
1433 Buffer const * const pbuf = d->parent();
1434 if (pbuf && scope != UpdateChildOnly)
1435 return pbuf->getBibfilesCache();
1437 // We update the cache when first used instead of at loading time.
1438 if (d->bibfilesCache_.empty())
1439 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1441 return d->bibfilesCache_;
1445 BiblioInfo const & Buffer::masterBibInfo() const
1447 // if this is a child document and the parent is already loaded
1448 // use the parent's list instead [ale990412]
1449 Buffer const * const tmp = masterBuffer();
1452 return tmp->masterBibInfo();
1453 return localBibInfo();
1457 BiblioInfo const & Buffer::localBibInfo() const
1459 if (d->bibinfoCacheValid_) {
1460 support::FileNameList const & bibfilesCache = getBibfilesCache();
1461 // compare the cached timestamps with the actual ones.
1462 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1463 support::FileNameList::const_iterator en = bibfilesCache.end();
1464 for (; ei != en; ++ ei) {
1465 time_t lastw = ei->lastModified();
1466 if (lastw != d->bibfileStatus_[*ei]) {
1467 d->bibinfoCacheValid_ = false;
1468 d->bibfileStatus_[*ei] = lastw;
1474 if (!d->bibinfoCacheValid_) {
1475 d->bibinfo_.clear();
1476 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1477 it->fillWithBibKeys(d->bibinfo_, it);
1478 d->bibinfoCacheValid_ = true;
1484 bool Buffer::isDepClean(string const & name) const
1486 DepClean::const_iterator const it = d->dep_clean.find(name);
1487 if (it == d->dep_clean.end())
1493 void Buffer::markDepClean(string const & name)
1495 d->dep_clean[name] = true;
1499 bool Buffer::dispatch(string const & command, bool * result)
1501 return dispatch(lyxaction.lookupFunc(command), result);
1505 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1507 bool dispatched = true;
1509 switch (func.action) {
1510 case LFUN_BUFFER_EXPORT: {
1511 bool const tmp = doExport(to_utf8(func.argument()), false);
1517 case LFUN_BRANCH_ACTIVATE:
1518 case LFUN_BRANCH_DEACTIVATE: {
1519 BranchList & branchList = params().branchlist();
1520 docstring const branchName = func.argument();
1521 // the case without a branch name is handled elsewhere
1522 if (branchName.empty()) {
1526 Branch * branch = branchList.find(branchName);
1528 LYXERR0("Branch " << branchName << " does not exist.");
1530 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1542 void Buffer::changeLanguage(Language const * from, Language const * to)
1544 LASSERT(from, /**/);
1547 for_each(par_iterator_begin(),
1549 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1553 bool Buffer::isMultiLingual() const
1555 ParConstIterator end = par_iterator_end();
1556 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1557 if (it->isMultiLingual(params()))
1564 DocIterator Buffer::getParFromID(int const id) const
1566 Buffer * buf = const_cast<Buffer *>(this);
1568 // John says this is called with id == -1 from undo
1569 lyxerr << "getParFromID(), id: " << id << endl;
1570 return doc_iterator_end(buf);
1573 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1574 if (it.paragraph().id() == id)
1577 return doc_iterator_end(buf);
1581 bool Buffer::hasParWithID(int const id) const
1583 return !getParFromID(id).atEnd();
1587 ParIterator Buffer::par_iterator_begin()
1589 return ParIterator(doc_iterator_begin(this));
1593 ParIterator Buffer::par_iterator_end()
1595 return ParIterator(doc_iterator_end(this));
1599 ParConstIterator Buffer::par_iterator_begin() const
1601 return ParConstIterator(doc_iterator_begin(this));
1605 ParConstIterator Buffer::par_iterator_end() const
1607 return ParConstIterator(doc_iterator_end(this));
1611 Language const * Buffer::language() const
1613 return params().language;
1617 docstring const Buffer::B_(string const & l10n) const
1619 return params().B_(l10n);
1623 bool Buffer::isClean() const
1625 return d->lyx_clean;
1629 bool Buffer::isBakClean() const
1631 return d->bak_clean;
1635 bool Buffer::isExternallyModified(CheckMethod method) const
1637 LASSERT(d->filename.exists(), /**/);
1638 // if method == timestamp, check timestamp before checksum
1639 return (method == checksum_method
1640 || d->timestamp_ != d->filename.lastModified())
1641 && d->checksum_ != d->filename.checksum();
1645 void Buffer::saveCheckSum(FileName const & file) const
1647 if (file.exists()) {
1648 d->timestamp_ = file.lastModified();
1649 d->checksum_ = file.checksum();
1651 // in the case of save to a new file.
1658 void Buffer::markClean() const
1660 if (!d->lyx_clean) {
1661 d->lyx_clean = true;
1664 // if the .lyx file has been saved, we don't need an
1666 d->bak_clean = true;
1670 void Buffer::markBakClean() const
1672 d->bak_clean = true;
1676 void Buffer::setUnnamed(bool flag)
1682 bool Buffer::isUnnamed() const
1688 // FIXME: this function should be moved to buffer_pimpl.C
1689 void Buffer::markDirty()
1692 d->lyx_clean = false;
1695 d->bak_clean = false;
1697 DepClean::iterator it = d->dep_clean.begin();
1698 DepClean::const_iterator const end = d->dep_clean.end();
1700 for (; it != end; ++it)
1705 FileName Buffer::fileName() const
1711 string Buffer::absFileName() const
1713 return d->filename.absFilename();
1717 string Buffer::filePath() const
1719 return d->filename.onlyPath().absFilename() + "/";
1723 bool Buffer::isReadonly() const
1725 return d->read_only;
1729 void Buffer::setParent(Buffer const * buffer)
1731 // Avoids recursive include.
1732 d->setParent(buffer == this ? 0 : buffer);
1737 Buffer const * Buffer::parent() const
1743 void Buffer::collectRelatives(BufferSet & bufs) const
1747 parent()->collectRelatives(bufs);
1749 // loop over children
1750 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1751 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1752 for (; it != end; ++it)
1753 bufs.insert(const_cast<Buffer *>(it->first));
1757 std::vector<Buffer const *> Buffer::allRelatives() const
1760 collectRelatives(bufs);
1761 BufferSet::iterator it = bufs.begin();
1762 std::vector<Buffer const *> ret;
1763 for (; it != bufs.end(); ++it)
1769 Buffer const * Buffer::masterBuffer() const
1771 Buffer const * const pbuf = d->parent();
1775 return pbuf->masterBuffer();
1779 bool Buffer::isChild(Buffer * child) const
1781 return d->children_positions.find(child) != d->children_positions.end();
1785 DocIterator Buffer::firstChildPosition(Buffer const * child)
1787 Impl::BufferPositionMap::iterator it;
1788 it = d->children_positions.find(child);
1789 if (it == d->children_positions.end())
1790 return DocIterator(this);
1795 std::vector<Buffer *> Buffer::getChildren() const
1797 std::vector<Buffer *> clist;
1798 // loop over children
1799 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1800 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1801 for (; it != end; ++it) {
1802 Buffer * child = const_cast<Buffer *>(it->first);
1803 clist.push_back(child);
1804 // there might be grandchildren
1805 std::vector<Buffer *> glist = child->getChildren();
1806 for (vector<Buffer *>::const_iterator git = glist.begin();
1807 git != glist.end(); ++git)
1808 clist.push_back(*git);
1814 template<typename M>
1815 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1820 typename M::iterator it = m.lower_bound(x);
1821 if (it == m.begin())
1829 MacroData const * Buffer::getBufferMacro(docstring const & name,
1830 DocIterator const & pos) const
1832 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1834 // if paragraphs have no macro context set, pos will be empty
1838 // we haven't found anything yet
1839 DocIterator bestPos = par_iterator_begin();
1840 MacroData const * bestData = 0;
1842 // find macro definitions for name
1843 Impl::NamePositionScopeMacroMap::iterator nameIt
1844 = d->macros.find(name);
1845 if (nameIt != d->macros.end()) {
1846 // find last definition in front of pos or at pos itself
1847 Impl::PositionScopeMacroMap::const_iterator it
1848 = greatest_below(nameIt->second, pos);
1849 if (it != nameIt->second.end()) {
1851 // scope ends behind pos?
1852 if (pos < it->second.first) {
1853 // Looks good, remember this. If there
1854 // is no external macro behind this,
1855 // we found the right one already.
1856 bestPos = it->first;
1857 bestData = &it->second.second;
1861 // try previous macro if there is one
1862 if (it == nameIt->second.begin())
1869 // find macros in included files
1870 Impl::PositionScopeBufferMap::const_iterator it
1871 = greatest_below(d->position_to_children, pos);
1872 if (it == d->position_to_children.end())
1873 // no children before
1877 // do we know something better (i.e. later) already?
1878 if (it->first < bestPos )
1881 // scope ends behind pos?
1882 if (pos < it->second.first) {
1883 // look for macro in external file
1884 d->macro_lock = true;
1885 MacroData const * data
1886 = it->second.second->getMacro(name, false);
1887 d->macro_lock = false;
1889 bestPos = it->first;
1895 // try previous file if there is one
1896 if (it == d->position_to_children.begin())
1901 // return the best macro we have found
1906 MacroData const * Buffer::getMacro(docstring const & name,
1907 DocIterator const & pos, bool global) const
1912 // query buffer macros
1913 MacroData const * data = getBufferMacro(name, pos);
1917 // If there is a master buffer, query that
1918 Buffer const * const pbuf = d->parent();
1920 d->macro_lock = true;
1921 MacroData const * macro = pbuf->getMacro(
1922 name, *this, false);
1923 d->macro_lock = false;
1929 data = MacroTable::globalMacros().get(name);
1938 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1940 // set scope end behind the last paragraph
1941 DocIterator scope = par_iterator_begin();
1942 scope.pit() = scope.lastpit() + 1;
1944 return getMacro(name, scope, global);
1948 MacroData const * Buffer::getMacro(docstring const & name,
1949 Buffer const & child, bool global) const
1951 // look where the child buffer is included first
1952 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1953 if (it == d->children_positions.end())
1956 // check for macros at the inclusion position
1957 return getMacro(name, it->second, global);
1961 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1963 pit_type lastpit = it.lastpit();
1965 // look for macros in each paragraph
1966 while (it.pit() <= lastpit) {
1967 Paragraph & par = it.paragraph();
1969 // iterate over the insets of the current paragraph
1970 InsetList const & insets = par.insetList();
1971 InsetList::const_iterator iit = insets.begin();
1972 InsetList::const_iterator end = insets.end();
1973 for (; iit != end; ++iit) {
1974 it.pos() = iit->pos;
1976 // is it a nested text inset?
1977 if (iit->inset->asInsetText()) {
1978 // Inset needs its own scope?
1979 InsetText const * itext = iit->inset->asInsetText();
1980 bool newScope = itext->isMacroScope();
1982 // scope which ends just behind the inset
1983 DocIterator insetScope = it;
1986 // collect macros in inset
1987 it.push_back(CursorSlice(*iit->inset));
1988 updateMacros(it, newScope ? insetScope : scope);
1993 // is it an external file?
1994 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1995 // get buffer of external file
1996 InsetInclude const & inset =
1997 static_cast<InsetInclude const &>(*iit->inset);
1998 d->macro_lock = true;
1999 Buffer * child = inset.getChildBuffer();
2000 d->macro_lock = false;
2004 // register its position, but only when it is
2005 // included first in the buffer
2006 if (d->children_positions.find(child) ==
2007 d->children_positions.end())
2008 d->children_positions[child] = it;
2010 // register child with its scope
2011 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2015 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2019 MathMacroTemplate & macroTemplate =
2020 static_cast<MathMacroTemplate &>(*iit->inset);
2021 MacroContext mc(*this, it);
2022 macroTemplate.updateToContext(mc);
2025 bool valid = macroTemplate.validMacro();
2026 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2027 // then the BufferView's cursor will be invalid in
2028 // some cases which leads to crashes.
2033 d->macros[macroTemplate.name()][it] =
2034 Impl::ScopeMacro(scope, MacroData(*this, it));
2044 void Buffer::updateMacros() const
2049 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2051 // start with empty table
2053 d->children_positions.clear();
2054 d->position_to_children.clear();
2056 // Iterate over buffer, starting with first paragraph
2057 // The scope must be bigger than any lookup DocIterator
2058 // later. For the global lookup, lastpit+1 is used, hence
2059 // we use lastpit+2 here.
2060 DocIterator it = par_iterator_begin();
2061 DocIterator outerScope = it;
2062 outerScope.pit() = outerScope.lastpit() + 2;
2063 updateMacros(it, outerScope);
2067 void Buffer::updateMacroInstances() const
2069 LYXERR(Debug::MACROS, "updateMacroInstances for "
2070 << d->filename.onlyFileName());
2071 DocIterator it = doc_iterator_begin(this);
2072 DocIterator end = doc_iterator_end(this);
2073 for (; it != end; it.forwardPos()) {
2074 // look for MathData cells in InsetMathNest insets
2075 Inset * inset = it.nextInset();
2079 InsetMath * minset = inset->asInsetMath();
2083 // update macro in all cells of the InsetMathNest
2084 DocIterator::idx_type n = minset->nargs();
2085 MacroContext mc = MacroContext(*this, it);
2086 for (DocIterator::idx_type i = 0; i < n; ++i) {
2087 MathData & data = minset->cell(i);
2088 data.updateMacros(0, mc);
2094 void Buffer::listMacroNames(MacroNameSet & macros) const
2099 d->macro_lock = true;
2101 // loop over macro names
2102 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2103 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2104 for (; nameIt != nameEnd; ++nameIt)
2105 macros.insert(nameIt->first);
2107 // loop over children
2108 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2109 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2110 for (; it != end; ++it)
2111 it->first->listMacroNames(macros);
2114 Buffer const * const pbuf = d->parent();
2116 pbuf->listMacroNames(macros);
2118 d->macro_lock = false;
2122 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2124 Buffer const * const pbuf = d->parent();
2129 pbuf->listMacroNames(names);
2132 MacroNameSet::iterator it = names.begin();
2133 MacroNameSet::iterator end = names.end();
2134 for (; it != end; ++it) {
2136 MacroData const * data =
2137 pbuf->getMacro(*it, *this, false);
2139 macros.insert(data);
2141 // we cannot access the original MathMacroTemplate anymore
2142 // here to calls validate method. So we do its work here manually.
2143 // FIXME: somehow make the template accessible here.
2144 if (data->optionals() > 0)
2145 features.require("xargs");
2151 Buffer::References & Buffer::references(docstring const & label)
2154 return const_cast<Buffer *>(masterBuffer())->references(label);
2156 RefCache::iterator it = d->ref_cache_.find(label);
2157 if (it != d->ref_cache_.end())
2158 return it->second.second;
2160 static InsetLabel const * dummy_il = 0;
2161 static References const dummy_refs;
2162 it = d->ref_cache_.insert(
2163 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2164 return it->second.second;
2168 Buffer::References const & Buffer::references(docstring const & label) const
2170 return const_cast<Buffer *>(this)->references(label);
2174 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2176 masterBuffer()->d->ref_cache_[label].first = il;
2180 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2182 return masterBuffer()->d->ref_cache_[label].first;
2186 void Buffer::clearReferenceCache() const
2189 d->ref_cache_.clear();
2193 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2196 //FIXME: This does not work for child documents yet.
2197 LASSERT(code == CITE_CODE, /**/);
2198 // Check if the label 'from' appears more than once
2199 vector<docstring> labels;
2201 BiblioInfo const & keys = masterBibInfo();
2202 BiblioInfo::const_iterator bit = keys.begin();
2203 BiblioInfo::const_iterator bend = keys.end();
2205 for (; bit != bend; ++bit)
2207 labels.push_back(bit->first);
2210 if (count(labels.begin(), labels.end(), from) > 1)
2213 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2214 if (it->lyxCode() == code) {
2215 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2216 docstring const oldValue = inset.getParam(paramName);
2217 if (oldValue == from)
2218 inset.setParam(paramName, to);
2224 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2225 pit_type par_end, bool full_source) const
2227 OutputParams runparams(¶ms().encoding());
2228 runparams.nice = true;
2229 runparams.flavor = OutputParams::LATEX;
2230 runparams.linelen = lyxrc.plaintext_linelen;
2231 // No side effect of file copying and image conversion
2232 runparams.dryrun = true;
2236 os << "% " << _("Preview source code") << "\n\n";
2237 d->texrow.newline();
2238 d->texrow.newline();
2240 writeDocBookSource(os, absFileName(), runparams, false);
2242 // latex or literate
2243 writeLaTeXSource(os, string(), runparams, true, true);
2245 runparams.par_begin = par_begin;
2246 runparams.par_end = par_end;
2247 if (par_begin + 1 == par_end) {
2249 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2253 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2254 convert<docstring>(par_begin),
2255 convert<docstring>(par_end - 1))
2258 d->texrow.newline();
2259 d->texrow.newline();
2260 // output paragraphs
2262 docbookParagraphs(paragraphs(), *this, os, runparams);
2264 // latex or literate
2265 latexParagraphs(*this, text(), os, d->texrow, runparams);
2270 ErrorList & Buffer::errorList(string const & type) const
2272 static ErrorList emptyErrorList;
2273 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2274 if (I == d->errorLists.end())
2275 return emptyErrorList;
2281 void Buffer::updateTocItem(std::string const & type,
2282 DocIterator const & dit) const
2285 gui_->updateTocItem(type, dit);
2289 void Buffer::structureChanged() const
2292 gui_->structureChanged();
2296 void Buffer::errors(string const & err) const
2303 void Buffer::message(docstring const & msg) const
2310 void Buffer::setBusy(bool on) const
2317 void Buffer::setReadOnly(bool on) const
2320 d->wa_->setReadOnly(on);
2324 void Buffer::updateTitles() const
2327 d->wa_->updateTitles();
2331 void Buffer::resetAutosaveTimers() const
2334 gui_->resetAutosaveTimers();
2338 bool Buffer::hasGuiDelegate() const
2344 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2353 class AutoSaveBuffer : public ForkedProcess {
2356 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2357 : buffer_(buffer), fname_(fname) {}
2359 virtual boost::shared_ptr<ForkedProcess> clone() const
2361 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2366 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2367 from_utf8(fname_.absFilename())));
2368 return run(DontWait);
2372 virtual int generateChild();
2374 Buffer const & buffer_;
2379 int AutoSaveBuffer::generateChild()
2381 // tmp_ret will be located (usually) in /tmp
2382 // will that be a problem?
2383 // Note that this calls ForkedCalls::fork(), so it's
2384 // ok cross-platform.
2385 pid_t const pid = fork();
2386 // If you want to debug the autosave
2387 // you should set pid to -1, and comment out the fork.
2388 if (pid != 0 && pid != -1)
2391 // pid = -1 signifies that lyx was unable
2392 // to fork. But we will do the save
2394 bool failed = false;
2395 FileName const tmp_ret = FileName::tempName("lyxauto");
2396 if (!tmp_ret.empty()) {
2397 buffer_.writeFile(tmp_ret);
2398 // assume successful write of tmp_ret
2399 if (!tmp_ret.moveTo(fname_))
2405 // failed to write/rename tmp_ret so try writing direct
2406 if (!buffer_.writeFile(fname_)) {
2407 // It is dangerous to do this in the child,
2408 // but safe in the parent, so...
2409 if (pid == -1) // emit message signal.
2410 buffer_.message(_("Autosave failed!"));
2414 if (pid == 0) // we are the child so...
2423 // Perfect target for a thread...
2424 void Buffer::autoSave() const
2426 if (isBakClean() || isReadonly()) {
2427 // We don't save now, but we'll try again later
2428 resetAutosaveTimers();
2432 // emit message signal.
2433 message(_("Autosaving current document..."));
2435 // create autosave filename
2436 string fname = filePath();
2438 fname += d->filename.onlyFileName();
2441 AutoSaveBuffer autosave(*this, FileName(fname));
2445 resetAutosaveTimers();
2449 string Buffer::bufferFormat() const
2455 if (params().encoding().package() == Encoding::japanese)
2461 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2462 string & result_file) const
2464 string backend_format;
2465 OutputParams runparams(¶ms().encoding());
2466 runparams.flavor = OutputParams::LATEX;
2467 runparams.linelen = lyxrc.plaintext_linelen;
2468 vector<string> backs = backends();
2469 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2470 // Get shortest path to format
2471 Graph::EdgePath path;
2472 for (vector<string>::const_iterator it = backs.begin();
2473 it != backs.end(); ++it) {
2474 Graph::EdgePath p = theConverters().getPath(*it, format);
2475 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2476 backend_format = *it;
2481 runparams.flavor = theConverters().getFlavor(path);
2483 Alert::error(_("Couldn't export file"),
2484 bformat(_("No information for exporting the format %1$s."),
2485 formats.prettyName(format)));
2489 backend_format = format;
2490 // FIXME: Don't hardcode format names here, but use a flag
2491 if (backend_format == "pdflatex")
2492 runparams.flavor = OutputParams::PDFLATEX;
2495 string filename = latexName(false);
2496 filename = addName(temppath(), filename);
2497 filename = changeExtension(filename,
2498 formats.extension(backend_format));
2501 updateMacroInstances();
2503 // Plain text backend
2504 if (backend_format == "text")
2505 writePlaintextFile(*this, FileName(filename), runparams);
2507 else if (backend_format == "lyx")
2508 writeFile(FileName(filename));
2510 else if (isDocBook()) {
2511 runparams.nice = !put_in_tempdir;
2512 makeDocBookFile(FileName(filename), runparams);
2515 else if (backend_format == format) {
2516 runparams.nice = true;
2517 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2519 } else if (!lyxrc.tex_allows_spaces
2520 && contains(filePath(), ' ')) {
2521 Alert::error(_("File name error"),
2522 _("The directory path to the document cannot contain spaces."));
2525 runparams.nice = false;
2526 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2530 string const error_type = (format == "program")
2531 ? "Build" : bufferFormat();
2532 ErrorList & error_list = d->errorLists[error_type];
2533 string const ext = formats.extension(format);
2534 FileName const tmp_result_file(changeExtension(filename, ext));
2535 bool const success = theConverters().convert(this, FileName(filename),
2536 tmp_result_file, FileName(absFileName()), backend_format, format,
2538 // Emit the signal to show the error list.
2539 if (format != backend_format)
2544 if (put_in_tempdir) {
2545 result_file = tmp_result_file.absFilename();
2549 result_file = changeExtension(absFileName(), ext);
2550 // We need to copy referenced files (e. g. included graphics
2551 // if format == "dvi") to the result dir.
2552 vector<ExportedFile> const files =
2553 runparams.exportdata->externalFiles(format);
2554 string const dest = onlyPath(result_file);
2555 CopyStatus status = SUCCESS;
2556 for (vector<ExportedFile>::const_iterator it = files.begin();
2557 it != files.end() && status != CANCEL; ++it) {
2558 string const fmt = formats.getFormatFromFile(it->sourceName);
2559 status = copyFile(fmt, it->sourceName,
2560 makeAbsPath(it->exportName, dest),
2561 it->exportName, status == FORCE);
2563 if (status == CANCEL) {
2564 message(_("Document export cancelled."));
2565 } else if (tmp_result_file.exists()) {
2566 // Finally copy the main file
2567 status = copyFile(format, tmp_result_file,
2568 FileName(result_file), result_file,
2570 message(bformat(_("Document exported as %1$s "
2572 formats.prettyName(format),
2573 makeDisplayPath(result_file)));
2575 // This must be a dummy converter like fax (bug 1888)
2576 message(bformat(_("Document exported as %1$s"),
2577 formats.prettyName(format)));
2584 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2587 return doExport(format, put_in_tempdir, result_file);
2591 bool Buffer::preview(string const & format) const
2594 if (!doExport(format, true, result_file))
2596 return formats.view(*this, FileName(result_file), format);
2600 bool Buffer::isExportable(string const & format) const
2602 vector<string> backs = backends();
2603 for (vector<string>::const_iterator it = backs.begin();
2604 it != backs.end(); ++it)
2605 if (theConverters().isReachable(*it, format))
2611 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2613 vector<string> backs = backends();
2614 vector<Format const *> result =
2615 theConverters().getReachable(backs[0], only_viewable, true);
2616 for (vector<string>::const_iterator it = backs.begin() + 1;
2617 it != backs.end(); ++it) {
2618 vector<Format const *> r =
2619 theConverters().getReachable(*it, only_viewable, false);
2620 result.insert(result.end(), r.begin(), r.end());
2626 vector<string> Buffer::backends() const
2629 if (params().baseClass()->isTeXClassAvailable()) {
2630 v.push_back(bufferFormat());
2631 // FIXME: Don't hardcode format names here, but use a flag
2632 if (v.back() == "latex")
2633 v.push_back("pdflatex");
2635 v.push_back("text");
2641 bool Buffer::readFileHelper(FileName const & s)
2643 // File information about normal file
2645 docstring const file = makeDisplayPath(s.absFilename(), 50);
2646 docstring text = bformat(_("The specified document\n%1$s"
2647 "\ncould not be read."), file);
2648 Alert::error(_("Could not read document"), text);
2652 // Check if emergency save file exists and is newer.
2653 FileName const e(s.absFilename() + ".emergency");
2655 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2656 docstring const file = makeDisplayPath(s.absFilename(), 20);
2657 docstring const text =
2658 bformat(_("An emergency save of the document "
2660 "Recover emergency save?"), file);
2661 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2662 _("&Recover"), _("&Load Original"),
2666 // the file is not saved if we load the emergency file.
2676 // Now check if autosave file is newer.
2677 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2679 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2680 docstring const file = makeDisplayPath(s.absFilename(), 20);
2681 docstring const text =
2682 bformat(_("The backup of the document "
2683 "%1$s is newer.\n\nLoad the "
2684 "backup instead?"), file);
2685 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2686 _("&Load backup"), _("Load &original"),
2690 // the file is not saved if we load the autosave file.
2694 // Here we delete the autosave
2705 bool Buffer::loadLyXFile(FileName const & s)
2707 if (s.isReadableFile()) {
2708 if (readFileHelper(s)) {
2709 lyxvc().file_found_hook(s);
2710 if (!s.isWritable())
2715 docstring const file = makeDisplayPath(s.absFilename(), 20);
2716 // Here we probably should run
2717 if (LyXVC::file_not_found_hook(s)) {
2718 docstring const text =
2719 bformat(_("Do you want to retrieve the document"
2720 " %1$s from version control?"), file);
2721 int const ret = Alert::prompt(_("Retrieve from version control?"),
2722 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2725 // How can we know _how_ to do the checkout?
2726 // With the current VC support it has to be,
2727 // a RCS file since CVS do not have special ,v files.
2729 return loadLyXFile(s);
2737 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2739 TeXErrors::Errors::const_iterator cit = terr.begin();
2740 TeXErrors::Errors::const_iterator end = terr.end();
2742 for (; cit != end; ++cit) {
2745 int errorRow = cit->error_in_line;
2746 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2752 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2753 } while (found && id_start == id_end && pos_start == pos_end);
2755 errorList.push_back(ErrorItem(cit->error_desc,
2756 cit->error_text, id_start, pos_start, pos_end));
2761 void Buffer::setBuffersForInsets() const
2763 inset().setBuffer(const_cast<Buffer &>(*this));
2767 void Buffer::updateLabels(UpdateScope scope) const
2769 // Use the master text class also for child documents
2770 Buffer const * const master = masterBuffer();
2771 DocumentClass const & textclass = master->params().documentClass();
2773 // keep the buffers to be children in this set. If the call from the
2774 // master comes back we can see which of them were actually seen (i.e.
2775 // via an InsetInclude). The remaining ones in the set need still be updated.
2776 static std::set<Buffer const *> bufToUpdate;
2777 if (scope == UpdateMaster) {
2778 // If this is a child document start with the master
2779 if (master != this) {
2780 bufToUpdate.insert(this);
2781 master->updateLabels();
2782 // Do this here in case the master has no gui associated with it. Then,
2783 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
2787 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2788 if (bufToUpdate.find(this) == bufToUpdate.end())
2792 // start over the counters in the master
2793 textclass.counters().reset();
2796 // update will be done below for this buffer
2797 bufToUpdate.erase(this);
2799 // update all caches
2800 clearReferenceCache();
2803 Buffer & cbuf = const_cast<Buffer &>(*this);
2805 LASSERT(!text().paragraphs().empty(), /**/);
2808 ParIterator parit = cbuf.par_iterator_begin();
2809 updateLabels(parit);
2812 // TocBackend update will be done later.
2815 cbuf.tocBackend().update();
2816 if (scope == UpdateMaster)
2817 cbuf.structureChanged();
2821 static depth_type getDepth(DocIterator const & it)
2823 depth_type depth = 0;
2824 for (size_t i = 0 ; i < it.depth() ; ++i)
2825 if (!it[i].inset().inMathed())
2826 depth += it[i].paragraph().getDepth() + 1;
2827 // remove 1 since the outer inset does not count
2831 static depth_type getItemDepth(ParIterator const & it)
2833 Paragraph const & par = *it;
2834 LabelType const labeltype = par.layout().labeltype;
2836 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
2839 // this will hold the lowest depth encountered up to now.
2840 depth_type min_depth = getDepth(it);
2841 ParIterator prev_it = it;
2844 --prev_it.top().pit();
2846 // start of nested inset: go to outer par
2848 if (prev_it.empty()) {
2849 // start of document: nothing to do
2854 // We search for the first paragraph with same label
2855 // that is not more deeply nested.
2856 Paragraph & prev_par = *prev_it;
2857 depth_type const prev_depth = getDepth(prev_it);
2858 if (labeltype == prev_par.layout().labeltype) {
2859 if (prev_depth < min_depth)
2860 return prev_par.itemdepth + 1;
2861 if (prev_depth == min_depth)
2862 return prev_par.itemdepth;
2864 min_depth = min(min_depth, prev_depth);
2865 // small optimization: if we are at depth 0, we won't
2866 // find anything else
2867 if (prev_depth == 0)
2873 static bool needEnumCounterReset(ParIterator const & it)
2875 Paragraph const & par = *it;
2876 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
2877 depth_type const cur_depth = par.getDepth();
2878 ParIterator prev_it = it;
2879 while (prev_it.pit()) {
2880 --prev_it.top().pit();
2881 Paragraph const & prev_par = *prev_it;
2882 if (prev_par.getDepth() <= cur_depth)
2883 return prev_par.layout().labeltype != LABEL_ENUMERATE;
2885 // start of nested inset: reset
2890 // set the label of a paragraph. This includes the counters.
2891 static void setLabel(Buffer const & buf, ParIterator & it)
2893 BufferParams const & bp = buf.masterBuffer()->params();
2894 DocumentClass const & textclass = bp.documentClass();
2895 Paragraph & par = it.paragraph();
2896 Layout const & layout = par.layout();
2897 Counters & counters = textclass.counters();
2899 if (par.params().startOfAppendix()) {
2900 // FIXME: only the counter corresponding to toplevel
2901 // sectionning should be reset
2903 counters.appendix(true);
2905 par.params().appendix(counters.appendix());
2907 // Compute the item depth of the paragraph
2908 par.itemdepth = getItemDepth(it);
2910 if (layout.margintype == MARGIN_MANUAL) {
2911 if (par.params().labelWidthString().empty())
2912 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
2914 par.params().labelWidthString(docstring());
2917 switch(layout.labeltype) {
2919 if (layout.toclevel <= bp.secnumdepth
2920 && (layout.latextype != LATEX_ENVIRONMENT
2921 || isFirstInSequence(it.pit(), it.plist()))) {
2922 counters.step(layout.counter);
2923 par.params().labelString(
2924 par.expandLabel(layout, bp));
2926 par.params().labelString(docstring());
2929 case LABEL_ITEMIZE: {
2930 // At some point of time we should do something more
2931 // clever here, like:
2932 // par.params().labelString(
2933 // bp.user_defined_bullet(par.itemdepth).getText());
2934 // for now, use a simple hardcoded label
2935 docstring itemlabel;
2936 switch (par.itemdepth) {
2938 itemlabel = char_type(0x2022);
2941 itemlabel = char_type(0x2013);
2944 itemlabel = char_type(0x2217);
2947 itemlabel = char_type(0x2219); // or 0x00b7
2950 par.params().labelString(itemlabel);
2954 case LABEL_ENUMERATE: {
2955 // FIXME: Yes I know this is a really, really! bad solution
2957 docstring enumcounter = from_ascii("enum");
2959 switch (par.itemdepth) {
2968 enumcounter += "iv";
2971 // not a valid enumdepth...
2975 // Maybe we have to reset the enumeration counter.
2976 if (needEnumCounterReset(it))
2977 counters.reset(enumcounter);
2979 counters.step(enumcounter);
2983 switch (par.itemdepth) {
2985 format = N_("\\arabic{enumi}.");
2988 format = N_("(\\alph{enumii})");
2991 format = N_("\\roman{enumiii}.");
2994 format = N_("\\Alph{enumiv}.");
2997 // not a valid enumdepth...
3001 par.params().labelString(counters.counterLabel(
3002 par.translateIfPossible(from_ascii(format), bp)));
3007 case LABEL_SENSITIVE: {
3008 string const & type = counters.current_float();
3009 docstring full_label;
3011 full_label = buf.B_("Senseless!!! ");
3013 docstring name = buf.B_(textclass.floats().getType(type).name());
3014 if (counters.hasCounter(from_utf8(type))) {
3015 counters.step(from_utf8(type));
3016 full_label = bformat(from_ascii("%1$s %2$s:"),
3018 counters.theCounter(from_utf8(type)));
3020 full_label = bformat(from_ascii("%1$s #:"), name);
3022 par.params().labelString(full_label);
3026 case LABEL_NO_LABEL:
3027 par.params().labelString(docstring());
3031 case LABEL_TOP_ENVIRONMENT:
3032 case LABEL_CENTERED_TOP_ENVIRONMENT:
3035 par.params().labelString(
3036 par.translateIfPossible(layout.labelstring(), bp));
3042 void Buffer::updateLabels(ParIterator & parit) const
3044 LASSERT(parit.pit() == 0, /**/);
3046 // set the position of the text in the buffer to be able
3047 // to resolve macros in it. This has nothing to do with
3048 // labels, but by putting it here we avoid implementing
3049 // a whole bunch of traversal routines just for this call.
3050 parit.text()->setMacrocontextPosition(parit);
3052 depth_type maxdepth = 0;
3053 pit_type const lastpit = parit.lastpit();
3054 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3055 // reduce depth if necessary
3056 parit->params().depth(min(parit->params().depth(), maxdepth));
3057 maxdepth = parit->getMaxDepthAfter();
3059 // set the counter for this paragraph
3060 setLabel(*this, parit);
3063 InsetList::const_iterator iit = parit->insetList().begin();
3064 InsetList::const_iterator end = parit->insetList().end();
3065 for (; iit != end; ++iit) {
3066 parit.pos() = iit->pos;
3067 iit->inset->updateLabels(parit);
3073 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3074 docstring & word) const
3076 bool inword = false;
3077 bool ignoreword = false;
3081 while (to.depth()) {
3088 lang_code = to.paragraph().getFontSettings(params(),
3089 to.pos()).language()->code();
3091 // Insets like optional hyphens and ligature
3092 // break are part of a word.
3093 if (!to.paragraph().isInset(to.pos())) {
3094 char_type const c = to.paragraph().getChar(to.pos());
3099 } else { // !isLetter(cur)
3100 if (inword && !word.empty() && !ignoreword)