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