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