OpenTTD Source 20261112-master-gbcbec5e63f
autocompletion.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11
12#include "autocompletion.h"
13
14#include "safeguards.h"
15
20{
21 /* We are pressing TAB for the first time after reset. */
22 if (this->suggestions.empty()) {
23 this->InitSuggestions(this->textbuf->GetText());
24 if (this->suggestions.empty()) {
25 return false;
26 }
27 this->ApplySuggestion(prefix, suggestions[0]);
28 return true;
29 }
30
31 /* We are pressing TAB again on the same text. */
32 if (this->current_suggestion_index + 1 < this->suggestions.size()) {
33 this->ApplySuggestion(prefix, this->suggestions[++this->current_suggestion_index]);
34 } else {
35 /* We are out of options, restore original text. */
36 this->textbuf->Assign(initial_buf);
37 this->Reset();
38 }
39 return true;
40}
41
42void AutoCompletion::Reset()
43{
44 this->prefix = "";
45 this->query = "";
46 this->initial_buf.clear();
47 this->suggestions.clear();
48 this->current_suggestion_index = 0;
49}
50
51void AutoCompletion::InitSuggestions(std::string_view text)
52{
53 this->initial_buf = text;
54 size_t space_pos = this->initial_buf.find_last_of(' ');
55 this->query = this->initial_buf;
56 if (space_pos == std::string::npos) {
57 this->prefix = "";
58 } else {
59 this->prefix = this->query.substr(0, space_pos + 1);
60 this->query.remove_prefix(space_pos + 1);
61 }
62
63 this->suggestions = this->GetSuggestions(prefix, query);
64 this->current_suggestion_index = 0;
65}
Generic auto-completion engine.
virtual std::vector< std::string > GetSuggestions(std::string_view prefix, std::string_view query)=0
Get suggestions for auto completion with the given 'query' input text.
virtual void ApplySuggestion(std::string_view prefix, std::string_view suggestion)=0
Format the given suggestion after the given prefix, and write that to the buffer.
std::string_view query
Last token of the text. This is used to based the suggestions on.
std::string_view prefix
Prefix of the text before the last space.
std::string initial_buf
Value of text buffer when we started current suggestion session.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.