]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
589c4500e4cb2232166abcea728202f9b76fd9e8
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "OutputEnums.h"
16 #include "OutputParams.h"
17
18 #include "insets/InsetCode.h"
19
20 #include "support/strfwd.h"
21 #include "support/types.h"
22
23 #include <map>
24 #include <list>
25 #include <set>
26 #include <string>
27 #include <vector>
28
29
30 namespace lyx {
31
32 class BiblioInfo;
33 class BibTeXInfo;
34 class BufferParams;
35 class DispatchResult;
36 class DocIterator;
37 class docstring_list;
38 class ErrorList;
39 class FuncRequest;
40 class FuncStatus;
41 class Inset;
42 class InsetLabel;
43 class InsetRef;
44 class Font;
45 class Format;
46 class Lexer;
47 class Text;
48 class LyXVC;
49 class LaTeXFeatures;
50 class Language;
51 class MacroData;
52 class MacroNameSet;
53 class MacroSet;
54 class OutputParams;
55 class Paragraph;
56 class ParConstIterator;
57 class ParIterator;
58 class ParagraphList;
59 class TeXErrors;
60 class TexRow;
61 class TocBackend;
62 class Undo;
63 class WordLangTuple;
64
65 namespace frontend {
66 class GuiBufferDelegate;
67 class WorkAreaManager;
68 }
69
70 namespace support {
71 class FileName;
72 class FileNameList;
73 }
74
75 namespace graphics {
76 class PreviewLoader;
77 }
78
79
80 class Buffer;
81 typedef std::list<Buffer *> ListOfBuffers;
82
83
84 /** The buffer object.
85  * This is the buffer object. It contains all the informations about
86  * a document loaded into LyX.
87  * The buffer object owns the Text (wrapped in an InsetText), which
88  * contains the individual paragraphs of the document.
89  *
90  *
91  * I am not sure if the class is complete or
92  * minimal, probably not.
93  * \author Lars Gullik Bjønnes
94  */
95 class Buffer {
96 public:
97         /// What type of log will \c getLogName() return?
98         enum LogType {
99                 latexlog, ///< LaTeX log
100                 buildlog  ///< Literate build log
101         };
102
103         /// Result of \c readFile()
104         enum ReadStatus {
105                 ReadSuccess,
106                 ReadCancel,
107                 // failures
108                 ReadFailure,
109                 ReadWrongVersion,
110                 ReadFileNotFound,
111                 ReadVCError,
112                 ReadAutosaveFailure,            
113                 ReadEmergencyFailure,
114                 ReadNoLyXFormat,
115                 ReadDocumentFailure,
116                 // lyx2lyx
117                 LyX2LyXNoTempFile,
118                 LyX2LyXNotFound,
119                 LyX2LyXOlderFormat,
120                 LyX2LyXNewerFormat,
121                 // other
122                 ReadOriginal
123         };
124
125         enum ExportStatus {
126                 // export
127                 ExportSuccess,
128                 ExportError,
129                 ExportNoPathToFormat,
130                 ExportTexPathHasSpaces,
131                 ExportConverterError,
132                 // preview
133                 PreviewSuccess,
134                 PreviewError
135         };
136
137         /// Method to check if a file is externally modified, used by
138         /// isExternallyModified()
139         /**
140          * timestamp is fast but inaccurate. For example, the granularity
141          * of timestamp on a FAT filesystem is 2 second. Also, various operations
142          * may touch the timestamp of a file even when its content is unchanged.
143          *
144          * checksum is accurate but slow, which can be a problem when it is
145          * frequently used, or used for a large file on a slow (network) file
146          * system.
147          *
148          * FIXME: replace this method with support/FileMonitor.
149          */
150         enum CheckMethod {
151                 checksum_method, ///< Use file checksum
152                 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
153         };
154
155         ///
156         enum UpdateScope {
157                 UpdateMaster,
158                 UpdateChildOnly
159         };
160
161         /// Constructor
162         explicit Buffer(std::string const & file, bool readonly = false,
163                 Buffer const * cloned_buffer = 0);
164
165         /// Destructor
166         ~Buffer();
167
168         ///
169         Buffer * clone() const;
170         ///
171         bool isClone() const;
172
173         /** High-level interface to buffer functionality.
174             This function parses a command string and executes it.
175         */
176         void dispatch(std::string const & command, DispatchResult & result);
177
178         /// Maybe we know the function already by number...
179         void dispatch(FuncRequest const & func, DispatchResult & result);
180
181         /// Can this function be exectued?
182         /// \return true if we made a decision
183         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
184
185         ///
186         DocIterator getParFromID(int id) const;
187         /// do we have a paragraph with this id?
188         bool hasParWithID(int id) const;
189
190         ///
191         frontend::WorkAreaManager & workAreaManager() const;
192
193         /** Save file.
194             Takes care of auto-save files and backup file if requested.
195             Returns \c true if the save is successful, \c false otherwise.
196         */
197         bool save() const;
198         /// Renames and saves the buffer
199         bool saveAs(support::FileName const & fn);
200
201         /// Write document to stream. Returns \c false if unsuccessful.
202         bool write(std::ostream &) const;
203         /// Write file. Returns \c false if unsuccessful.
204         bool writeFile(support::FileName const &) const;
205
206         /// \name Functions involved in reading files/strings.
207         //@{
208         /// Loads the LyX file into the buffer. This function
209         /// tries to extract the file from version control if it
210         /// cannot be found. If it can be found, it will try to
211         /// read an emergency save file or an autosave file.
212         /// \sa loadThisLyXFile
213         ReadStatus loadLyXFile();
214         /// Loads the LyX file \c fn into the buffer. If you want
215         /// to check for files in a version control container,
216         /// emergency or autosave files, one should use \c loadLyXFile.
217         /// /sa loadLyXFile
218         ReadStatus loadThisLyXFile(support::FileName const & fn);
219         /// read a new document from a string
220         bool readString(std::string const &);
221         /// Reloads the LyX file
222         ReadStatus reload();
223 //FIXME: The following function should be private
224 //private:
225         /// read the header, returns number of unknown tokens
226         int readHeader(Lexer & lex);
227
228 private:
229         ///
230         typedef std::map<Buffer const *, Buffer *> BufferMap;
231         ///
232         void clone(BufferMap &) const;
233         /// save timestamp and checksum of the given file.
234         void saveCheckSum() const;      
235         /// read a new file
236         ReadStatus readFile(support::FileName const & fn);
237         /// Reads a file without header.
238         /// \param par if != 0 insert the file.
239         /// \return \c true if file is not completely read.
240         bool readDocument(Lexer &);
241         /// Try to extract the file from a version control container
242         /// before reading if the file cannot be found. This is only
243         /// implemented for RCS.
244         /// \sa LyXVC::file_not_found_hook
245         ReadStatus extractFromVC();
246         /// Reads the first tag of a LyX File and 
247         /// returns the file format number.
248         ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
249                 int & file_format) const;
250         /// Convert the LyX file to the LYX_FORMAT using
251         /// the lyx2lyx script and returns the filename
252         /// of the temporary file to be read
253         ReadStatus convertLyXFormat(support::FileName const & fn, 
254                 support::FileName & tmpfile, int from_format);
255         //@}
256
257 public:
258         /// \name Functions involved in autosave and emergency files.
259         //@{
260         /// Save an autosave file to #filename.lyx#
261         bool autoSave() const;  
262         /// save emergency file
263         /// \return a status message towards the user.
264         docstring emergencyWrite();
265
266 //FIXME:The following function should be private
267 //private:
268         ///
269         void removeAutosaveFile() const;
270         
271 private:
272         /// Try to load an autosave file associated to \c fn.
273         ReadStatus loadAutosave();
274         /// Try to load an emergency file associated to \c fn. 
275         ReadStatus loadEmergency();
276         /// Get the filename of the emergency file associated with the Buffer
277         support::FileName getEmergencyFileName() const;
278         /// Get the filename of the autosave file associated with the Buffer
279         support::FileName getAutosaveFileName() const;
280         ///
281         void moveAutosaveFile(support::FileName const & old) const;
282         //@}
283
284 public:
285         /// Fill in the ErrorList with the TeXErrors
286         void bufferErrors(TeXErrors const &, ErrorList &) const;
287
288         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
289         bool makeLaTeXFile(support::FileName const & filename,
290                            std::string const & original_path,
291                            OutputParams const &,
292                            bool output_preamble = true,
293                            bool output_body = true) const;
294         /** Export the buffer to LaTeX.
295             If \p os is a file stream, and params().inputenc is "auto" or
296             "default", and the buffer contains text in different languages
297             with more than one encoding, then this method will change the
298             encoding associated to \p os. Therefore you must not call this
299             method with a string stream if the output is supposed to go to a
300             file. \code
301             ofdocstream ofs;
302             otexstream os(ofs, texrow);
303             ofs.open("test.tex");
304             writeLaTeXSource(os, ...);
305             ofs.close();
306             \endcode is NOT equivalent to \code
307             odocstringstream oss;
308             otexstream os(oss, texrow);
309             writeLaTeXSource(os, ...);
310             ofdocstream ofs;
311             ofs.open("test.tex");
312             ofs << oss.str();
313             ofs.close();
314             \endcode
315          */
316         void writeLaTeXSource(otexstream & os,
317                            std::string const & original_path,
318                            OutputParams const &,
319                            bool output_preamble = true,
320                            bool output_body = true) const;
321         ///
322         void makeDocBookFile(support::FileName const & filename,
323                              OutputParams const & runparams_in,
324                              bool only_body = false) const;
325         ///
326         void writeDocBookSource(odocstream & os, std::string const & filename,
327                              OutputParams const & runparams_in,
328                              bool only_body = false) const;
329         ///
330         void makeLyXHTMLFile(support::FileName const & filename,
331                              OutputParams const & runparams_in) const;
332         ///
333         void writeLyXHTMLSource(odocstream & os,
334                              OutputParams const & runparams_in,
335                              bool only_body = false) const;
336         /// returns the main language for the buffer (document)
337         Language const * language() const;
338         /// get l10n translated to the buffers language
339         docstring const B_(std::string const & l10n) const;
340
341         ///
342         int runChktex();
343         /// return true if the main lyx file does not need saving
344         bool isClean() const;
345         ///
346         bool isDepClean(std::string const & name) const;
347
348         /// whether or not disk file has been externally modified
349         bool isExternallyModified(CheckMethod method) const;
350
351         /// mark the main lyx file as not needing saving
352         void markClean() const;
353
354         ///
355         void markDepClean(std::string const & name);
356
357         ///
358         void setUnnamed(bool flag = true);
359
360         /// Whether or not a filename has been assigned to this buffer
361         bool isUnnamed() const;
362
363         /// Whether or not this buffer is internal.
364         ///
365         /// An internal buffer does not contain a real document, but some auxiliary text segment.
366         /// It is not associated with a filename, it is never saved, thus it does not need to be
367         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
368         bool isInternal() const;
369
370         /// Mark this buffer as dirty.
371         void markDirty();
372
373         /// Returns the buffer's filename. It is always an absolute path.
374         support::FileName fileName() const;
375
376         /// Returns the buffer's filename. It is always an absolute path.
377         std::string absFileName() const;
378
379         /// Returns the the path where the buffer lives.
380         /// It is always an absolute path.
381         std::string filePath() const;
382
383         /** A transformed version of the file name, adequate for LaTeX.
384             \param no_path optional if \c true then the path is stripped.
385         */
386         std::string latexName(bool no_path = true) const;
387
388         /// Get the name and type of the log.
389         std::string logName(LogType * type = 0) const;
390
391         /// Set document's parent Buffer.
392         void setParent(Buffer const *);
393         Buffer const * parent() const;
394
395         /** Get the document's master (or \c this if this is not a
396             child document)
397          */
398         Buffer const * masterBuffer() const;
399
400         /// \return true if \p child is a child of this \c Buffer.
401         bool isChild(Buffer * child) const;
402         
403         /// \return true if this \c Buffer has children
404         bool hasChildren() const;
405         
406         /// \return a list of the direct children of this Buffer.
407         /// this list has no duplicates and is in the order in which
408         /// the children appear.
409         ListOfBuffers getChildren() const;
410         
411         /// \return a list of all descendents of this Buffer (children,
412         /// grandchildren, etc). this list has no duplicates and is in
413         /// the order in which the children appear.
414         ListOfBuffers getDescendents() const;
415
416         /// Collect all relative buffers, in the order in which they appear.
417         /// I.e., the "root" Buffer is first, then its first child, then any
418         /// of its children, etc. However, there are no duplicates in this
419         /// list.
420         /// This is "stable", too, in the sense that it returns the same
421         /// thing from whichever Buffer it is called.
422         ListOfBuffers allRelatives() const;
423
424         /// Is buffer read-only?
425         bool isReadonly() const;
426
427         /// Set buffer read-only flag
428         void setReadonly(bool flag = true);
429
430         /** Validate a buffer for LaTeX.
431             This validates the buffer, and returns a struct for use by
432             #makeLaTeX# and others. Its main use is to figure out what
433             commands and packages need to be included in the LaTeX file.
434             It (should) also check that the needed constructs are there
435             (i.e. that the \refs points to coresponding \labels). It
436             should perhaps inset "error" insets to help the user correct
437             obvious mistakes.
438         */
439         void validate(LaTeXFeatures &) const;
440
441         /// Reference information is cached in the Buffer, so we do not
442         /// have to check or read things over and over. 
443         ///
444         /// There are two caches.
445         ///
446         /// One is a cache of the BibTeX files from which reference info is
447         /// being gathered. This cache is PER BUFFER, and the cache for the
448         /// master essentially includes the cache for its children. This gets
449         /// invalidated when an InsetBibtex is created, deleted, or modified.
450         /// 
451         /// The other is a cache of the reference information itself. This
452         /// exists only in the master buffer, and when it needs to be updated,
453         /// the children add their information to the master's cache.
454         
455         /// Calling this method invalidates the cache and so requires a
456         /// re-read.
457         void invalidateBibinfoCache() const;
458         /// This invalidates the cache of files we need to check.
459         void invalidateBibfileCache() const;
460         /// Updates the cached bibliography information, checking first to see
461         /// whether the cache is valid. If so, we do nothing. If not, then we
462         /// reload all the BibTeX info.
463         /// Note that this operates on the master document.
464         void reloadBibInfoCache() const;
465         /// \return the bibliography information for this buffer's master,
466         /// or just for it, if it isn't a child.
467         BiblioInfo const & masterBibInfo() const;
468         /// collect bibliography info from the various insets in this buffer.
469         void collectBibKeys() const;
470         /// add some BiblioInfo to our cache
471         void addBiblioInfo(BiblioInfo const & bi) const;
472         /// add a single piece of bibliography info to our cache
473         void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
474         ///
475         bool citeLabelsValid() const;
476         ///
477         void getLabelList(std::vector<docstring> &) const;
478
479         ///
480         void changeLanguage(Language const * from, Language const * to);
481
482         ///
483         bool isMultiLingual() const;
484         ///
485         std::set<Language const *> getLanguages() const;
486
487         ///
488         BufferParams & params();
489         BufferParams const & params() const;
490
491         /** The list of paragraphs.
492             This is a linked list of paragraph, this list holds the
493             whole contents of the document.
494          */
495         ParagraphList & paragraphs();
496         ParagraphList const & paragraphs() const;
497
498         /// LyX version control object.
499         LyXVC & lyxvc();
500         LyXVC const & lyxvc() const;
501
502         /// Where to put temporary files.
503         std::string const temppath() const;
504
505         /// Used when typesetting to place errorboxes.
506         TexRow const & texrow() const;
507         TexRow & texrow();
508
509         ///
510         ParIterator par_iterator_begin();
511         ///
512         ParConstIterator par_iterator_begin() const;
513         ///
514         ParIterator par_iterator_end();
515         ///
516         ParConstIterator par_iterator_end() const;
517
518         // Position of the child buffer where it appears first in the master.
519         DocIterator firstChildPosition(Buffer const * child);
520
521         /** \returns true only when the file is fully loaded.
522          *  Used to prevent the premature generation of previews
523          *  and by the citation inset.
524          */
525         bool isFullyLoaded() const;
526         /// Set by buffer_funcs' newFile.
527         void setFullyLoaded(bool);
528
529         /// FIXME: Needed by RenderPreview.
530         graphics::PreviewLoader * loader() const;
531         /// Update the LaTeX preview snippets associated with this buffer
532         void updatePreviews() const;
533         /// Remove any previewed LaTeX snippets associated with this buffer
534         void removePreviews() const;
535
536         /// Our main text (inside the top InsetText)
537         Text & text() const;
538
539         /// Our top InsetText
540         Inset & inset() const;
541
542         //
543         // Macro handling
544         //
545         /// Collect macro definitions in paragraphs
546         void updateMacros() const;
547         /// Iterate through the whole buffer and try to resolve macros
548         void updateMacroInstances(UpdateType) const;
549
550         /// List macro names of this buffer, the parent and the children
551         void listMacroNames(MacroNameSet & macros) const;
552         /// Collect macros of the parent and its children in front of this buffer.
553         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
554
555         /// Return macro defined before pos (or in the master buffer)
556         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
557         /// Return macro defined anywhere in the buffer (or in the master buffer)
558         MacroData const * getMacro(docstring const & name, bool global = true) const;
559         /// Return macro defined before the inclusion of the child
560         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
561
562         /// Collect user macro names at loading time
563         typedef std::set<docstring> UserMacroSet;
564         mutable UserMacroSet usermacros;
565
566         /// Replace the inset contents for insets which InsetCode is equal
567         /// to the passed \p inset_code.
568         void changeRefsIfUnique(docstring const & from, docstring const & to,
569                 InsetCode code);
570
571         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
572         /// including preamble
573         void getSourceCode(odocstream & os, std::string const format,
574                            pit_type par_begin, pit_type par_end, bool full_source) const;
575
576         /// Access to error list.
577         /// This method is used only for GUI visualisation of Buffer related
578         /// errors (like parsing or LateX compilation). This method is const
579         /// because modifying the returned ErrorList does not touch the document
580         /// contents.
581         ErrorList & errorList(std::string const & type) const;
582
583         /// The Toc backend.
584         /// This is useful only for screen visualisation of the Buffer. This
585         /// method is const because modifying this backend does not touch
586         /// the document contents.
587         TocBackend & tocBackend() const;
588
589         ///
590         Undo & undo();
591
592         /// This function is called when the buffer is changed.
593         void changed(bool update_metrics) const;
594         ///
595         void setChild(DocIterator const & dit, Buffer * child);
596         ///
597         void updateTocItem(std::string const &, DocIterator const &) const;
598         /// This function is called when the buffer structure is changed.
599         void structureChanged() const;
600         /// This function is called when some parsing error shows up.
601         void errors(std::string const & err, bool from_master = false) const;
602         /// This function is called when the buffer busy status change.
603         void setBusy(bool on) const;
604         /// Update window titles of all users.
605         void updateTitles() const;
606         /// Reset autosave timers for all users.
607         void resetAutosaveTimers() const;
608         ///
609         void message(docstring const & msg) const;
610
611         ///
612         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
613         ///
614         bool hasGuiDelegate() const;
615
616         ///
617         bool doExport(std::string const & target, bool put_in_tempdir) const;
618         ///
619         bool preview(std::string const & format) const;
620
621 private:
622         /// target is a format name optionally followed by a space
623         /// and a destination file-name
624         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
625                 bool includeall, std::string & result_file) const;
626         ///
627         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
628                 bool includeall) const;
629         ///
630         ExportStatus preview(std::string const & format, bool includeall = false) const;
631
632 public:
633         /// mark the buffer as busy exporting something, or not
634         void setExportStatus(bool e) const;
635         ///
636         bool isExporting() const;
637
638         ///
639         typedef std::vector<std::pair<Inset *, ParIterator> > References;
640         References & references(docstring const & label);
641         References const & references(docstring const & label) const;
642         void clearReferenceCache() const;
643         void setInsetLabel(docstring const & label, InsetLabel const * il);
644         InsetLabel const * insetLabel(docstring const & label) const;
645
646         /// return a list of all used branches (also in children)
647         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
648
649         /// sets the buffer_ member for every inset in this buffer.
650         // FIXME This really shouldn't be needed, but at the moment it's not
651         // clear how to do it just for the individual pieces we need.
652         void setBuffersForInsets() const;
653         /// Updates screen labels and some other information associated with
654         /// insets and paragraphs. Actually, it's more like a general "recurse
655         /// through the Buffer" routine, that visits all the insets and paragraphs.
656         void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
657         /// \param scope: whether to start with the master document or just
658         /// do this one.
659         /// \param output: whether we are preparing for output.
660         void updateBuffer(UpdateScope scope, UpdateType utype) const;
661         /// 
662         void updateBuffer(ParIterator & parit, UpdateType utype) const;
663
664         /// Spellcheck starting from \p from.
665         /// \p from initial position, will then points to the next misspelled
666         ///    word.
667         /// \p to will points to the end of the next misspelled word.
668         /// \p word_lang will contain the found misspelled word.
669         /// \return progress if a new word was found.
670         int spellCheck(DocIterator & from, DocIterator & to,
671                 WordLangTuple & word_lang, docstring_list & suggestions) const;
672         ///
673         void checkChildBuffers();
674
675 private:
676         /// Change name of buffer. Updates "read-only" flag.
677         void setFileName(support::FileName const & fname);
678         ///
679         void getLanguages(std::set<Language const *> &) const;
680         /// Checks whether any of the referenced bibfiles have changed since the
681         /// last time we loaded the cache. Note that this does NOT update the
682         /// cached information.
683         void checkIfBibInfoCacheIsValid() const;
684         /// Update the list of all bibfiles in use (including bibfiles
685         /// of loaded child documents).
686         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
687         /// Return the list with all bibfiles in use (including bibfiles
688         /// of loaded child documents).
689         support::FileNameList const & 
690                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
691         ///
692         void collectChildren(ListOfBuffers & children, bool grand_children) const;
693
694         /// noncopyable
695         Buffer(Buffer const &);
696         void operator=(Buffer const &);
697
698         /// Use the Pimpl idiom to hide the internals.
699         class Impl;
700         /// The pointer never changes although *pimpl_'s contents may.
701         Impl * const d;
702 };
703
704
705 } // namespace lyx
706
707 #endif