Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Host/common/Editline.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- Editline.cpp ------------------------------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include <climits>
10
#include <iomanip>
11
12
#include "lldb/Host/Editline.h"
13
14
#include "lldb/Host/ConnectionFileDescriptor.h"
15
#include "lldb/Host/FileSystem.h"
16
#include "lldb/Host/Host.h"
17
#include "lldb/Utility/CompletionRequest.h"
18
#include "lldb/Utility/FileSpec.h"
19
#include "lldb/Utility/LLDBAssert.h"
20
#include "lldb/Utility/SelectHelper.h"
21
#include "lldb/Utility/Status.h"
22
#include "lldb/Utility/StreamString.h"
23
#include "lldb/Utility/StringList.h"
24
#include "lldb/Utility/Timeout.h"
25
26
#include "llvm/Support/FileSystem.h"
27
#include "llvm/Support/Threading.h"
28
29
using namespace lldb_private;
30
using namespace lldb_private::line_editor;
31
32
// Workaround for what looks like an OS X-specific issue, but other platforms
33
// may benefit from something similar if issues arise.  The libedit library
34
// doesn't explicitly initialize the curses termcap library, which it gets away
35
// with until TERM is set to VT100 where it stumbles over an implementation
36
// assumption that may not exist on other platforms.  The setupterm() function
37
// would normally require headers that don't work gracefully in this context,
38
// so the function declaration has been hoisted here.
39
#if defined(__APPLE__)
40
extern "C" {
41
int setupterm(char *term, int fildes, int *errret);
42
}
43
#define USE_SETUPTERM_WORKAROUND
44
#endif
45
46
// Editline uses careful cursor management to achieve the illusion of editing a
47
// multi-line block of text with a single line editor.  Preserving this
48
// illusion requires fairly careful management of cursor state.  Read and
49
// understand the relationship between DisplayInput(), MoveCursor(),
50
// SetCurrentLine(), and SaveEditedLine() before making changes.
51
52
/// https://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf
53
115
#define ESCAPE "\x1b"
54
/// Faint, decreased intensity or second colour.
55
1
#define ANSI_FAINT ESCAPE
"[2m"0
56
/// Normal colour or normal intensity (neither bold nor faint).
57
1
#define ANSI_UNFAINT ESCAPE
"[0m"0
58
1
#define ANSI_CLEAR_BELOW ESCAPE "[J"
59
#define ANSI_CLEAR_RIGHT ESCAPE "[K"
60
35
#define ANSI_SET_COLUMN_N ESCAPE "[%dG"
61
5
#define ANSI_UP_N_ROWS ESCAPE "[%dA"
62
0
#define ANSI_DOWN_N_ROWS ESCAPE "[%dB"
63
64
#if LLDB_EDITLINE_USE_WCHAR
65
66
5
#define EditLineConstString(str) L##str
67
#define EditLineStringFormatSpec "%ls"
68
69
#else
70
71
#define EditLineConstString(str) str
72
#define EditLineStringFormatSpec "%s"
73
74
// use #defines so wide version functions and structs will resolve to old
75
// versions for case of libedit not built with wide char support
76
#define history_w history
77
#define history_winit history_init
78
#define history_wend history_end
79
#define HistoryW History
80
#define HistEventW HistEvent
81
#define LineInfoW LineInfo
82
83
#define el_wgets el_gets
84
#define el_wgetc el_getc
85
#define el_wpush el_push
86
#define el_wparse el_parse
87
#define el_wset el_set
88
#define el_wget el_get
89
#define el_wline el_line
90
#define el_winsertstr el_insertstr
91
#define el_wdeletestr el_deletestr
92
93
#endif // #if LLDB_EDITLINE_USE_WCHAR
94
95
5
bool IsOnlySpaces(const EditLineStringType &content) {
96
5
  for (wchar_t ch : content) {
97
0
    if (ch != EditLineCharType(' '))
98
0
      return false;
99
0
  }
100
5
  return true;
101
5
}
102
103
0
static int GetOperation(HistoryOperation op) {
104
  // The naming used by editline for the history operations is counter
105
  // intuitive to how it's used in LLDB's editline implementation.
106
  //
107
  //  - The H_LAST returns the oldest entry in the history.
108
  //
109
  //  - The H_PREV operation returns the previous element in the history, which
110
  //    is newer than the current one.
111
  //
112
  //  - The H_CURR returns the current entry in the history.
113
  //
114
  //  - The H_NEXT operation returns the next element in the history, which is
115
  //    older than the current one.
116
  //
117
  //  - The H_FIRST returns the most recent entry in the history.
118
  //
119
  // The naming of the enum entries match the semantic meaning.
120
0
  switch(op) {
121
0
    case HistoryOperation::Oldest:
122
0
      return H_LAST;
123
0
    case HistoryOperation::Older:
124
0
      return H_NEXT;
125
0
    case HistoryOperation::Current:
126
0
      return H_CURR;
127
0
    case HistoryOperation::Newer:
128
0
      return H_PREV;
129
0
    case HistoryOperation::Newest:
130
0
      return H_FIRST;
131
0
  }
132
0
  llvm_unreachable("Fully covered switch!");
133
0
}
134
135
136
2
EditLineStringType CombineLines(const std::vector<EditLineStringType> &lines) {
137
2
  EditLineStringStreamType combined_stream;
138
6
  for (EditLineStringType line : lines) {
139
6
    combined_stream << line.c_str() << "\n";
140
6
  }
141
2
  return combined_stream.str();
142
2
}
143
144
26
std::vector<EditLineStringType> SplitLines(const EditLineStringType &input) {
145
26
  std::vector<EditLineStringType> result;
146
26
  size_t start = 0;
147
52
  while (start < input.length()) {
148
26
    size_t end = input.find('\n', start);
149
26
    if (end == std::string::npos) {
150
0
      result.push_back(input.substr(start));
151
0
      break;
152
0
    }
153
26
    result.push_back(input.substr(start, end - start));
154
26
    start = end + 1;
155
26
  }
156
  // Treat an empty history session as a single command of zero-length instead
157
  // of returning an empty vector.
158
26
  if (result.empty()) {
159
0
    result.emplace_back();
160
0
  }
161
26
  return result;
162
26
}
163
164
EditLineStringType FixIndentation(const EditLineStringType &line,
165
0
                                  int indent_correction) {
166
0
  if (indent_correction == 0)
167
0
    return line;
168
0
  if (indent_correction < 0)
169
0
    return line.substr(-indent_correction);
170
0
  return EditLineStringType(indent_correction, EditLineCharType(' ')) + line;
171
0
}
172
173
0
int GetIndentation(const EditLineStringType &line) {
174
0
  int space_count = 0;
175
0
  for (EditLineCharType ch : line) {
176
0
    if (ch != EditLineCharType(' '))
177
0
      break;
178
0
    ++space_count;
179
0
  }
180
0
  return space_count;
181
0
}
182
183
12
bool IsInputPending(FILE *file) {
184
  // FIXME: This will be broken on Windows if we ever re-enable Editline.  You
185
  // can't use select
186
  // on something that isn't a socket.  This will have to be re-written to not
187
  // use a FILE*, but instead use some kind of yet-to-be-created abstraction
188
  // that select-like functionality on non-socket objects.
189
12
  const int fd = fileno(file);
190
12
  SelectHelper select_helper;
191
12
  select_helper.SetTimeout(std::chrono::microseconds(0));
192
12
  select_helper.FDSetRead(fd);
193
12
  return select_helper.Select().Success();
194
12
}
195
196
namespace lldb_private {
197
namespace line_editor {
198
typedef std::weak_ptr<EditlineHistory> EditlineHistoryWP;
199
200
// EditlineHistory objects are sometimes shared between multiple Editline
201
// instances with the same program name.
202
203
class EditlineHistory {
204
private:
205
  // Use static GetHistory() function to get a EditlineHistorySP to one of
206
  // these objects
207
  EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries)
208
8
      : m_prefix(prefix) {
209
8
    m_history = history_winit();
210
8
    history_w(m_history, &m_event, H_SETSIZE, size);
211
8
    if (unique_entries)
212
8
      history_w(m_history, &m_event, H_SETUNIQUE, 1);
213
8
  }
214
215
16
  const char *GetHistoryFilePath() {
216
    // Compute the history path lazily.
217
16
    if (m_path.empty() && 
m_history8
&&
!m_prefix.empty()8
) {
218
8
      llvm::SmallString<128> lldb_history_file;
219
8
      FileSystem::Instance().GetHomeDirectory(lldb_history_file);
220
8
      llvm::sys::path::append(lldb_history_file, ".lldb");
221
222
      // LLDB stores its history in ~/.lldb/. If for some reason this directory
223
      // isn't writable or cannot be created, history won't be available.
224
8
      if (!llvm::sys::fs::create_directory(lldb_history_file)) {
225
8
#if LLDB_EDITLINE_USE_WCHAR
226
8
        std::string filename = m_prefix + "-widehistory";
227
#else
228
        std::string filename = m_prefix + "-history";
229
#endif
230
8
        llvm::sys::path::append(lldb_history_file, filename);
231
8
        m_path = std::string(lldb_history_file.str());
232
8
      }
233
8
    }
234
235
16
    if (m_path.empty())
236
0
      return nullptr;
237
238
16
    return m_path.c_str();
239
16
  }
240
241
public:
242
8
  ~EditlineHistory() {
243
8
    Save();
244
245
8
    if (m_history) {
246
8
      history_wend(m_history);
247
8
      m_history = nullptr;
248
8
    }
249
8
  }
250
251
8
  static EditlineHistorySP GetHistory(const std::string &prefix) {
252
8
    typedef std::map<std::string, EditlineHistoryWP> WeakHistoryMap;
253
8
    static std::recursive_mutex g_mutex;
254
8
    static WeakHistoryMap g_weak_map;
255
8
    std::lock_guard<std::recursive_mutex> guard(g_mutex);
256
8
    WeakHistoryMap::const_iterator pos = g_weak_map.find(prefix);
257
8
    EditlineHistorySP history_sp;
258
8
    if (pos != g_weak_map.end()) {
259
0
      history_sp = pos->second.lock();
260
0
      if (history_sp)
261
0
        return history_sp;
262
0
      g_weak_map.erase(pos);
263
0
    }
264
8
    history_sp.reset(new EditlineHistory(prefix, 800, true));
265
8
    g_weak_map[prefix] = history_sp;
266
8
    return history_sp;
267
8
  }
268
269
8
  bool IsValid() const { return m_history != nullptr; }
270
271
8
  HistoryW *GetHistoryPtr() { return m_history; }
272
273
28
  void Enter(const EditLineCharType *line_cstr) {
274
28
    if (m_history)
275
28
      history_w(m_history, &m_event, H_ENTER, line_cstr);
276
28
  }
277
278
8
  bool Load() {
279
8
    if (m_history) {
280
8
      const char *path = GetHistoryFilePath();
281
8
      if (path) {
282
8
        history_w(m_history, &m_event, H_LOAD, path);
283
8
        return true;
284
8
      }
285
8
    }
286
0
    return false;
287
8
  }
288
289
8
  bool Save() {
290
8
    if (m_history) {
291
8
      const char *path = GetHistoryFilePath();
292
8
      if (path) {
293
8
        history_w(m_history, &m_event, H_SAVE, path);
294
8
        return true;
295
8
      }
296
8
    }
297
0
    return false;
298
8
  }
299
300
protected:
301
  /// The history object.
302
  HistoryW *m_history = nullptr;
303
  /// The history event needed to contain all history events.
304
  HistEventW m_event;
305
  /// The prefix name (usually the editline program name) to use when
306
  /// loading/saving history.
307
  std::string m_prefix;
308
  /// Path to the history file.
309
  std::string m_path;
310
};
311
}
312
}
313
314
// Editline private methods
315
316
2
void Editline::SetBaseLineNumber(int line_number) {
317
2
  m_base_line_number = line_number;
318
2
  m_line_number_digits =
319
2
      std::max<int>(3, std::to_string(line_number).length() + 1);
320
2
}
321
322
418
std::string Editline::PromptForIndex(int line_index) {
323
418
  bool use_line_numbers = m_multiline_enabled && 
m_base_line_number > 0386
;
324
418
  std::string prompt = m_set_prompt;
325
418
  if (use_line_numbers && 
prompt.length() == 0110
)
326
0
    prompt = ": ";
327
418
  std::string continuation_prompt = prompt;
328
418
  if (m_set_continuation_prompt.length() > 0) {
329
0
    continuation_prompt = m_set_continuation_prompt;
330
331
    // Ensure that both prompts are the same length through space padding
332
0
    while (continuation_prompt.length() < prompt.length()) {
333
0
      continuation_prompt += ' ';
334
0
    }
335
0
    while (prompt.length() < continuation_prompt.length()) {
336
0
      prompt += ' ';
337
0
    }
338
0
  }
339
340
418
  if (use_line_numbers) {
341
110
    StreamString prompt_stream;
342
110
    prompt_stream.Printf(
343
110
        "%*d%s", m_line_number_digits, m_base_line_number + line_index,
344
110
        (line_index == 0) ? 
prompt.c_str()99
:
continuation_prompt.c_str()11
);
345
110
    return std::string(std::move(prompt_stream.GetString()));
346
110
  }
347
308
  return (line_index == 0) ? 
prompt306
:
continuation_prompt2
;
348
418
}
349
350
33
void Editline::SetCurrentLine(int line_index) {
351
33
  m_current_line_index = line_index;
352
33
  m_current_prompt = PromptForIndex(line_index);
353
33
}
354
355
313
int Editline::GetPromptWidth() { return (int)PromptForIndex(0).length(); }
356
357
2
bool Editline::IsEmacs() {
358
2
  const char *editor;
359
2
  el_get(m_editline, EL_EDITOR, &editor);
360
2
  return editor[0] == 'e';
361
2
}
362
363
0
bool Editline::IsOnlySpaces() {
364
0
  const LineInfoW *info = el_wline(m_editline);
365
0
  for (const EditLineCharType *character = info->buffer;
366
0
       character < info->lastchar; character++) {
367
0
    if (*character != ' ')
368
0
      return false;
369
0
  }
370
0
  return true;
371
0
}
372
373
48
int Editline::GetLineIndexForLocation(CursorLocation location, int cursor_row) {
374
48
  int line = 0;
375
48
  if (location == CursorLocation::EditingPrompt ||
376
48
      
location == CursorLocation::BlockEnd33
||
377
48
      
location == CursorLocation::EditingCursor20
) {
378
89
    for (unsigned index = 0; index < m_current_line_index; 
index++44
) {
379
44
      line += CountRowsForLine(m_input_lines[index]);
380
44
    }
381
45
    if (location == CursorLocation::EditingCursor) {
382
17
      line += cursor_row;
383
28
    } else if (location == CursorLocation::BlockEnd) {
384
25
      for (unsigned index = m_current_line_index; index < m_input_lines.size();
385
13
           
index++12
) {
386
12
        line += CountRowsForLine(m_input_lines[index]);
387
12
      }
388
13
      --line;
389
13
    }
390
45
  }
391
48
  return line;
392
48
}
393
394
24
void Editline::MoveCursor(CursorLocation from, CursorLocation to) {
395
24
  const LineInfoW *info = el_wline(m_editline);
396
24
  int editline_cursor_position =
397
24
      (int)((info->cursor - info->buffer) + GetPromptWidth());
398
24
  int editline_cursor_row = editline_cursor_position / m_terminal_width;
399
400
  // Determine relative starting and ending lines
401
24
  int fromLine = GetLineIndexForLocation(from, editline_cursor_row);
402
24
  int toLine = GetLineIndexForLocation(to, editline_cursor_row);
403
24
  if (toLine != fromLine) {
404
5
    fprintf(m_output_file,
405
5
            (toLine > fromLine) ? ANSI_DOWN_N_ROWS : ANSI_UP_N_ROWS,
406
5
            std::abs(toLine - fromLine));
407
5
  }
408
409
  // Determine target column
410
24
  int toColumn = 1;
411
24
  if (to == CursorLocation::EditingCursor) {
412
5
    toColumn =
413
5
        editline_cursor_position - (editline_cursor_row * m_terminal_width) + 1;
414
19
  } else if (to == CursorLocation::BlockEnd && 
!m_input_lines.empty()2
) {
415
2
    toColumn =
416
2
        ((m_input_lines[m_input_lines.size() - 1].length() + GetPromptWidth()) %
417
2
         80) +
418
2
        1;
419
2
  }
420
24
  fprintf(m_output_file, ANSI_SET_COLUMN_N, toColumn);
421
24
}
422
423
11
void Editline::DisplayInput(int firstIndex) {
424
11
  fprintf(m_output_file, ANSI_SET_COLUMN_N ANSI_CLEAR_BELOW, 1);
425
11
  int line_count = (int)m_input_lines.size();
426
11
  const char *faint = m_color_prompts ? ANSI_FAINT : "";
427
11
  const char *unfaint = m_color_prompts ? ANSI_UNFAINT : "";
428
429
27
  for (int index = firstIndex; index < line_count; 
index++16
) {
430
16
    fprintf(m_output_file, "%s"
431
16
                           "%s"
432
16
                           "%s" EditLineStringFormatSpec " ",
433
16
            faint, PromptForIndex(index).c_str(), unfaint,
434
16
            m_input_lines[index].c_str());
435
16
    if (index < line_count - 1)
436
5
      fprintf(m_output_file, "\n");
437
16
  }
438
11
}
439
440
56
int Editline::CountRowsForLine(const EditLineStringType &content) {
441
56
  std::string prompt =
442
56
      PromptForIndex(0); // Prompt width is constant during an edit session
443
56
  int line_length = (int)(content.length() + prompt.length());
444
56
  return (line_length / m_terminal_width) + 1;
445
56
}
446
447
5
void Editline::SaveEditedLine() {
448
5
  const LineInfoW *info = el_wline(m_editline);
449
5
  m_input_lines[m_current_line_index] =
450
5
      EditLineStringType(info->buffer, info->lastchar - info->buffer);
451
5
}
452
453
4
StringList Editline::GetInputAsStringList(int line_count) {
454
4
  StringList lines;
455
13
  for (EditLineStringType line : m_input_lines) {
456
13
    if (line_count == 0)
457
0
      break;
458
13
#if LLDB_EDITLINE_USE_WCHAR
459
13
    lines.AppendString(m_utf8conv.to_bytes(line));
460
#else
461
    lines.AppendString(line);
462
#endif
463
13
    --line_count;
464
13
  }
465
4
  return lines;
466
4
}
467
468
0
unsigned char Editline::RecallHistory(HistoryOperation op) {
469
0
  assert(op == HistoryOperation::Older || op == HistoryOperation::Newer);
470
0
  if (!m_history_sp || !m_history_sp->IsValid())
471
0
    return CC_ERROR;
472
473
0
  HistoryW *pHistory = m_history_sp->GetHistoryPtr();
474
0
  HistEventW history_event;
475
0
  std::vector<EditLineStringType> new_input_lines;
476
477
  // Treat moving from the "live" entry differently
478
0
  if (!m_in_history) {
479
0
    switch (op) {
480
0
    case HistoryOperation::Newer:
481
0
      return CC_ERROR; // Can't go newer than the "live" entry
482
0
    case HistoryOperation::Older: {
483
0
      if (history_w(pHistory, &history_event,
484
0
                    GetOperation(HistoryOperation::Newest)) == -1)
485
0
        return CC_ERROR;
486
      // Save any edits to the "live" entry in case we return by moving forward
487
      // in history (it would be more bash-like to save over any current entry,
488
      // but libedit doesn't offer the ability to add entries anywhere except
489
      // the end.)
490
0
      SaveEditedLine();
491
0
      m_live_history_lines = m_input_lines;
492
0
      m_in_history = true;
493
0
    } break;
494
0
    default:
495
0
      llvm_unreachable("unsupported history direction");
496
0
    }
497
0
  } else {
498
0
    if (history_w(pHistory, &history_event, GetOperation(op)) == -1) {
499
0
      switch (op) {
500
0
      case HistoryOperation::Older:
501
        // Can't move earlier than the earliest entry.
502
0
        return CC_ERROR;
503
0
      case HistoryOperation::Newer:
504
        // Moving to newer-than-the-newest entry yields the "live" entry.
505
0
        new_input_lines = m_live_history_lines;
506
0
        m_in_history = false;
507
0
        break;
508
0
      default:
509
0
        llvm_unreachable("unsupported history direction");
510
0
      }
511
0
    }
512
0
  }
513
514
  // If we're pulling the lines from history, split them apart
515
0
  if (m_in_history)
516
0
    new_input_lines = SplitLines(history_event.str);
517
518
  // Erase the current edit session and replace it with a new one
519
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
520
0
  m_input_lines = new_input_lines;
521
0
  DisplayInput();
522
523
  // Prepare to edit the last line when moving to previous entry, or the first
524
  // line when moving to next entry
525
0
  switch (op) {
526
0
  case HistoryOperation::Older:
527
0
    m_current_line_index = (int)m_input_lines.size() - 1;
528
0
    break;
529
0
  case HistoryOperation::Newer:
530
0
    m_current_line_index = 0;
531
0
    break;
532
0
  default:
533
0
    llvm_unreachable("unsupported history direction");
534
0
  }
535
0
  SetCurrentLine(m_current_line_index);
536
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
537
0
  return CC_NEWLINE;
538
0
}
539
540
851
int Editline::GetCharacter(EditLineGetCharType *c) {
541
851
  const LineInfoW *info = el_wline(m_editline);
542
543
  // Paint a faint version of the desired prompt over the version libedit draws
544
  // (will only be requested if colors are supported)
545
851
  if (m_needs_prompt_repaint) {
546
1
    MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
547
1
    fprintf(m_output_file, "%s"
548
1
                           "%s"
549
1
                           "%s",
550
1
            ANSI_FAINT, Prompt(), ANSI_UNFAINT);
551
1
    MoveCursor(CursorLocation::EditingPrompt, CursorLocation::EditingCursor);
552
1
    m_needs_prompt_repaint = false;
553
1
  }
554
555
851
  if (m_multiline_enabled) {
556
    // Detect when the number of rows used for this input line changes due to
557
    // an edit
558
287
    int lineLength = (int)((info->lastchar - info->buffer) + GetPromptWidth());
559
287
    int new_line_rows = (lineLength / m_terminal_width) + 1;
560
287
    if (m_current_line_rows != -1 && 
new_line_rows != m_current_line_rows280
) {
561
      // Respond by repainting the current state from this line on
562
3
      MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
563
3
      SaveEditedLine();
564
3
      DisplayInput(m_current_line_index);
565
3
      MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
566
3
    }
567
287
    m_current_line_rows = new_line_rows;
568
287
  }
569
570
  // Read an actual character
571
851
  while (true) {
572
851
    lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess;
573
851
    char ch = 0;
574
575
851
    if (m_terminal_size_has_changed)
576
0
      ApplyTerminalSizeChange();
577
578
    // This mutex is locked by our caller (GetLine). Unlock it while we read a
579
    // character (blocking operation), so we do not hold the mutex
580
    // indefinitely. This gives a chance for someone to interrupt us. After
581
    // Read returns, immediately lock the mutex again and check if we were
582
    // interrupted.
583
851
    m_output_mutex.unlock();
584
851
    int read_count =
585
851
        m_input_connection.Read(&ch, 1, llvm::None, status, nullptr);
586
851
    m_output_mutex.lock();
587
851
    if (m_editor_status == EditorStatus::Interrupted) {
588
0
      while (read_count > 0 && status == lldb::eConnectionStatusSuccess)
589
0
        read_count =
590
0
            m_input_connection.Read(&ch, 1, llvm::None, status, nullptr);
591
0
      lldbassert(status == lldb::eConnectionStatusInterrupted);
592
0
      return 0;
593
0
    }
594
595
851
    if (read_count) {
596
851
      if (CompleteCharacter(ch, *c))
597
851
        return 1;
598
851
    } else {
599
0
      switch (status) {
600
0
      case lldb::eConnectionStatusSuccess: // Success
601
0
        break;
602
603
0
      case lldb::eConnectionStatusInterrupted:
604
0
        llvm_unreachable("Interrupts should have been handled above.");
605
606
0
      case lldb::eConnectionStatusError:        // Check GetError() for details
607
0
      case lldb::eConnectionStatusTimedOut:     // Request timed out
608
0
      case lldb::eConnectionStatusEndOfFile:    // End-of-file encountered
609
0
      case lldb::eConnectionStatusNoConnection: // No connection
610
0
      case lldb::eConnectionStatusLostConnection: // Lost connection while
611
                                                  // connected to a valid
612
                                                  // connection
613
0
        m_editor_status = EditorStatus::EndOfInput;
614
0
        return 0;
615
0
      }
616
0
    }
617
851
  }
618
851
}
619
620
41
const char *Editline::Prompt() {
621
41
  if (m_color_prompts)
622
2
    m_needs_prompt_repaint = true;
623
41
  return m_current_prompt.c_str();
624
41
}
625
626
5
unsigned char Editline::BreakLineCommand(int ch) {
627
  // Preserve any content beyond the cursor, truncate and save the current line
628
5
  const LineInfoW *info = el_wline(m_editline);
629
5
  auto current_line =
630
5
      EditLineStringType(info->buffer, info->cursor - info->buffer);
631
5
  auto new_line_fragment =
632
5
      EditLineStringType(info->cursor, info->lastchar - info->cursor);
633
5
  m_input_lines[m_current_line_index] = current_line;
634
635
  // Ignore whitespace-only extra fragments when breaking a line
636
5
  if (::IsOnlySpaces(new_line_fragment))
637
5
    new_line_fragment = EditLineConstString("");
638
639
  // Establish the new cursor position at the start of a line when inserting a
640
  // line break
641
5
  m_revert_cursor_index = 0;
642
643
  // Don't perform automatic formatting when pasting
644
5
  if (!IsInputPending(m_input_file)) {
645
    // Apply smart indentation
646
0
    if (m_fix_indentation_callback) {
647
0
      StringList lines = GetInputAsStringList(m_current_line_index + 1);
648
0
#if LLDB_EDITLINE_USE_WCHAR
649
0
      lines.AppendString(m_utf8conv.to_bytes(new_line_fragment));
650
#else
651
      lines.AppendString(new_line_fragment);
652
#endif
653
654
0
      int indent_correction = m_fix_indentation_callback(this, lines, 0);
655
0
      new_line_fragment = FixIndentation(new_line_fragment, indent_correction);
656
0
      m_revert_cursor_index = GetIndentation(new_line_fragment);
657
0
    }
658
0
  }
659
660
  // Insert the new line and repaint everything from the split line on down
661
5
  m_input_lines.insert(m_input_lines.begin() + m_current_line_index + 1,
662
5
                       new_line_fragment);
663
5
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
664
5
  DisplayInput(m_current_line_index);
665
666
  // Reposition the cursor to the right line and prepare to edit the new line
667
5
  SetCurrentLine(m_current_line_index + 1);
668
5
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
669
5
  return CC_NEWLINE;
670
5
}
671
672
7
unsigned char Editline::EndOrAddLineCommand(int ch) {
673
  // Don't perform end of input detection when pasting, always treat this as a
674
  // line break
675
7
  if (IsInputPending(m_input_file)) {
676
5
    return BreakLineCommand(ch);
677
5
  }
678
679
  // Save any edits to this line
680
2
  SaveEditedLine();
681
682
  // If this is the end of the last line, consider whether to add a line
683
  // instead
684
2
  const LineInfoW *info = el_wline(m_editline);
685
2
  if (m_current_line_index == m_input_lines.size() - 1 &&
686
2
      info->cursor == info->lastchar) {
687
2
    if (m_is_input_complete_callback) {
688
2
      auto lines = GetInputAsStringList();
689
2
      if (!m_is_input_complete_callback(this, lines)) {
690
0
        return BreakLineCommand(ch);
691
0
      }
692
693
      // The completion test is allowed to change the input lines when complete
694
2
      m_input_lines.clear();
695
8
      for (unsigned index = 0; index < lines.GetSize(); 
index++6
) {
696
6
#if LLDB_EDITLINE_USE_WCHAR
697
6
        m_input_lines.insert(m_input_lines.end(),
698
6
                             m_utf8conv.from_bytes(lines[index]));
699
#else
700
        m_input_lines.insert(m_input_lines.end(), lines[index]);
701
#endif
702
6
      }
703
2
    }
704
2
  }
705
2
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
706
2
  fprintf(m_output_file, "\n");
707
2
  m_editor_status = EditorStatus::Complete;
708
2
  return CC_NEWLINE;
709
2
}
710
711
0
unsigned char Editline::DeleteNextCharCommand(int ch) {
712
0
  LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
713
714
  // Just delete the next character normally if possible
715
0
  if (info->cursor < info->lastchar) {
716
0
    info->cursor++;
717
0
    el_deletestr(m_editline, 1);
718
0
    return CC_REFRESH;
719
0
  }
720
721
  // Fail when at the end of the last line, except when ^D is pressed on the
722
  // line is empty, in which case it is treated as EOF
723
0
  if (m_current_line_index == m_input_lines.size() - 1) {
724
0
    if (ch == 4 && info->buffer == info->lastchar) {
725
0
      fprintf(m_output_file, "^D\n");
726
0
      m_editor_status = EditorStatus::EndOfInput;
727
0
      return CC_EOF;
728
0
    }
729
0
    return CC_ERROR;
730
0
  }
731
732
  // Prepare to combine this line with the one below
733
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
734
735
  // Insert the next line of text at the cursor and restore the cursor position
736
0
  const EditLineCharType *cursor = info->cursor;
737
0
  el_winsertstr(m_editline, m_input_lines[m_current_line_index + 1].c_str());
738
0
  info->cursor = cursor;
739
0
  SaveEditedLine();
740
741
  // Delete the extra line
742
0
  m_input_lines.erase(m_input_lines.begin() + m_current_line_index + 1);
743
744
  // Clear and repaint from this line on down
745
0
  DisplayInput(m_current_line_index);
746
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
747
0
  return CC_REFRESH;
748
0
}
749
750
0
unsigned char Editline::DeletePreviousCharCommand(int ch) {
751
0
  LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
752
753
  // Just delete the previous character normally when not at the start of a
754
  // line
755
0
  if (info->cursor > info->buffer) {
756
0
    el_deletestr(m_editline, 1);
757
0
    return CC_REFRESH;
758
0
  }
759
760
  // No prior line and no prior character?  Let the user know
761
0
  if (m_current_line_index == 0)
762
0
    return CC_ERROR;
763
764
  // No prior character, but prior line?  Combine with the line above
765
0
  SaveEditedLine();
766
0
  SetCurrentLine(m_current_line_index - 1);
767
0
  auto priorLine = m_input_lines[m_current_line_index];
768
0
  m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
769
0
  m_input_lines[m_current_line_index] =
770
0
      priorLine + m_input_lines[m_current_line_index];
771
772
  // Repaint from the new line down
773
0
  fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
774
0
          CountRowsForLine(priorLine), 1);
775
0
  DisplayInput(m_current_line_index);
776
777
  // Put the cursor back where libedit expects it to be before returning to
778
  // editing by telling libedit about the newly inserted text
779
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
780
0
  el_winsertstr(m_editline, priorLine.c_str());
781
0
  return CC_REDISPLAY;
782
0
}
783
784
0
unsigned char Editline::PreviousLineCommand(int ch) {
785
0
  SaveEditedLine();
786
787
0
  if (m_current_line_index == 0) {
788
0
    return RecallHistory(HistoryOperation::Older);
789
0
  }
790
791
  // Start from a known location
792
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
793
794
  // Treat moving up from a blank last line as a deletion of that line
795
0
  if (m_current_line_index == m_input_lines.size() - 1 && IsOnlySpaces()) {
796
0
    m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
797
0
    fprintf(m_output_file, ANSI_CLEAR_BELOW);
798
0
  }
799
800
0
  SetCurrentLine(m_current_line_index - 1);
801
0
  fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
802
0
          CountRowsForLine(m_input_lines[m_current_line_index]), 1);
803
0
  return CC_NEWLINE;
804
0
}
805
806
0
unsigned char Editline::NextLineCommand(int ch) {
807
0
  SaveEditedLine();
808
809
  // Handle attempts to move down from the last line
810
0
  if (m_current_line_index == m_input_lines.size() - 1) {
811
    // Don't add an extra line if the existing last line is blank, move through
812
    // history instead
813
0
    if (IsOnlySpaces()) {
814
0
      return RecallHistory(HistoryOperation::Newer);
815
0
    }
816
817
    // Determine indentation for the new line
818
0
    int indentation = 0;
819
0
    if (m_fix_indentation_callback) {
820
0
      StringList lines = GetInputAsStringList();
821
0
      lines.AppendString("");
822
0
      indentation = m_fix_indentation_callback(this, lines, 0);
823
0
    }
824
0
    m_input_lines.insert(
825
0
        m_input_lines.end(),
826
0
        EditLineStringType(indentation, EditLineCharType(' ')));
827
0
  }
828
829
  // Move down past the current line using newlines to force scrolling if
830
  // needed
831
0
  SetCurrentLine(m_current_line_index + 1);
832
0
  const LineInfoW *info = el_wline(m_editline);
833
0
  int cursor_position = (int)((info->cursor - info->buffer) + GetPromptWidth());
834
0
  int cursor_row = cursor_position / m_terminal_width;
835
0
  for (int line_count = 0; line_count < m_current_line_rows - cursor_row;
836
0
       line_count++) {
837
0
    fprintf(m_output_file, "\n");
838
0
  }
839
0
  return CC_NEWLINE;
840
0
}
841
842
0
unsigned char Editline::PreviousHistoryCommand(int ch) {
843
0
  SaveEditedLine();
844
845
0
  return RecallHistory(HistoryOperation::Older);
846
0
}
847
848
0
unsigned char Editline::NextHistoryCommand(int ch) {
849
0
  SaveEditedLine();
850
851
0
  return RecallHistory(HistoryOperation::Newer);
852
0
}
853
854
0
unsigned char Editline::FixIndentationCommand(int ch) {
855
0
  if (!m_fix_indentation_callback)
856
0
    return CC_NORM;
857
858
  // Insert the character typed before proceeding
859
0
  EditLineCharType inserted[] = {(EditLineCharType)ch, 0};
860
0
  el_winsertstr(m_editline, inserted);
861
0
  LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
862
0
  int cursor_position = info->cursor - info->buffer;
863
864
  // Save the edits and determine the correct indentation level
865
0
  SaveEditedLine();
866
0
  StringList lines = GetInputAsStringList(m_current_line_index + 1);
867
0
  int indent_correction =
868
0
      m_fix_indentation_callback(this, lines, cursor_position);
869
870
  // If it is already correct no special work is needed
871
0
  if (indent_correction == 0)
872
0
    return CC_REFRESH;
873
874
  // Change the indentation level of the line
875
0
  std::string currentLine = lines.GetStringAtIndex(m_current_line_index);
876
0
  if (indent_correction > 0) {
877
0
    currentLine = currentLine.insert(0, indent_correction, ' ');
878
0
  } else {
879
0
    currentLine = currentLine.erase(0, -indent_correction);
880
0
  }
881
0
#if LLDB_EDITLINE_USE_WCHAR
882
0
  m_input_lines[m_current_line_index] = m_utf8conv.from_bytes(currentLine);
883
#else
884
  m_input_lines[m_current_line_index] = currentLine;
885
#endif
886
887
  // Update the display to reflect the change
888
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
889
0
  DisplayInput(m_current_line_index);
890
891
  // Reposition the cursor back on the original line and prepare to restart
892
  // editing with a new cursor position
893
0
  SetCurrentLine(m_current_line_index);
894
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
895
0
  m_revert_cursor_index = cursor_position + indent_correction;
896
0
  return CC_NEWLINE;
897
0
}
898
899
7
unsigned char Editline::RevertLineCommand(int ch) {
900
7
  el_winsertstr(m_editline, m_input_lines[m_current_line_index].c_str());
901
7
  if (m_revert_cursor_index >= 0) {
902
5
    LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
903
5
    info->cursor = info->buffer + m_revert_cursor_index;
904
5
    if (info->cursor > info->lastchar) {
905
0
      info->cursor = info->lastchar;
906
0
    }
907
5
    m_revert_cursor_index = -1;
908
5
  }
909
7
  return CC_REFRESH;
910
7
}
911
912
0
unsigned char Editline::BufferStartCommand(int ch) {
913
0
  SaveEditedLine();
914
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
915
0
  SetCurrentLine(0);
916
0
  m_revert_cursor_index = 0;
917
0
  return CC_NEWLINE;
918
0
}
919
920
0
unsigned char Editline::BufferEndCommand(int ch) {
921
0
  SaveEditedLine();
922
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
923
0
  SetCurrentLine((int)m_input_lines.size() - 1);
924
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
925
0
  return CC_NEWLINE;
926
0
}
927
928
/// Prints completions and their descriptions to the given file. Only the
929
/// completions in the interval [start, end) are printed.
930
static void
931
PrintCompletion(FILE *output_file,
932
                llvm::ArrayRef<CompletionResult::Completion> results,
933
0
                size_t max_len) {
934
0
  for (const CompletionResult::Completion &c : results) {
935
0
    fprintf(output_file, "\t%-*s", (int)max_len, c.GetCompletion().c_str());
936
0
    if (!c.GetDescription().empty())
937
0
      fprintf(output_file, " -- %s", c.GetDescription().c_str());
938
0
    fprintf(output_file, "\n");
939
0
  }
940
0
}
941
942
static void
943
DisplayCompletions(::EditLine *editline, FILE *output_file,
944
0
                   llvm::ArrayRef<CompletionResult::Completion> results) {
945
0
  assert(!results.empty());
946
947
0
  fprintf(output_file, "\n" ANSI_CLEAR_BELOW "Available completions:\n");
948
0
  const size_t page_size = 40;
949
0
  bool all = false;
950
951
0
  auto longest =
952
0
      std::max_element(results.begin(), results.end(), [](auto &c1, auto &c2) {
953
0
        return c1.GetCompletion().size() < c2.GetCompletion().size();
954
0
      });
955
956
0
  const size_t max_len = longest->GetCompletion().size();
957
958
0
  if (results.size() < page_size) {
959
0
    PrintCompletion(output_file, results, max_len);
960
0
    return;
961
0
  }
962
963
0
  size_t cur_pos = 0;
964
0
  while (cur_pos < results.size()) {
965
0
    size_t remaining = results.size() - cur_pos;
966
0
    size_t next_size = all ? remaining : std::min(page_size, remaining);
967
968
0
    PrintCompletion(output_file, results.slice(cur_pos, next_size), max_len);
969
970
0
    cur_pos += next_size;
971
972
0
    if (cur_pos >= results.size())
973
0
      break;
974
975
0
    fprintf(output_file, "More (Y/n/a): ");
976
0
    char reply = 'n';
977
0
    int got_char = el_getc(editline, &reply);
978
0
    fprintf(output_file, "\n");
979
0
    if (got_char == -1 || reply == 'n')
980
0
      break;
981
0
    if (reply == 'a')
982
0
      all = true;
983
0
  }
984
0
}
985
986
0
unsigned char Editline::TabCommand(int ch) {
987
0
  if (!m_completion_callback)
988
0
    return CC_ERROR;
989
990
0
  const LineInfo *line_info = el_line(m_editline);
991
992
0
  llvm::StringRef line(line_info->buffer,
993
0
                       line_info->lastchar - line_info->buffer);
994
0
  unsigned cursor_index = line_info->cursor - line_info->buffer;
995
0
  CompletionResult result;
996
0
  CompletionRequest request(line, cursor_index, result);
997
998
0
  m_completion_callback(request);
999
1000
0
  llvm::ArrayRef<CompletionResult::Completion> results = result.GetResults();
1001
1002
0
  StringList completions;
1003
0
  result.GetMatches(completions);
1004
1005
0
  if (results.size() == 0)
1006
0
    return CC_ERROR;
1007
1008
0
  if (results.size() == 1) {
1009
0
    CompletionResult::Completion completion = results.front();
1010
0
    switch (completion.GetMode()) {
1011
0
    case CompletionMode::Normal: {
1012
0
      std::string to_add = completion.GetCompletion();
1013
      // Terminate the current argument with a quote if it started with a quote.
1014
0
      if (!request.GetParsedLine().empty() && request.GetParsedArg().IsQuoted())
1015
0
        to_add.push_back(request.GetParsedArg().GetQuoteChar());
1016
0
      to_add.push_back(' ');
1017
0
      el_deletestr(m_editline, request.GetCursorArgumentPrefix().size());
1018
0
      el_insertstr(m_editline, to_add.c_str());
1019
      // Clear all the autosuggestion parts if the only single space can be completed.
1020
0
      if (to_add == " ")
1021
0
        return CC_REDISPLAY;
1022
0
      return CC_REFRESH;
1023
0
    }
1024
0
    case CompletionMode::Partial: {
1025
0
      std::string to_add = completion.GetCompletion();
1026
0
      to_add = to_add.substr(request.GetCursorArgumentPrefix().size());
1027
0
      el_insertstr(m_editline, to_add.c_str());
1028
0
      break;
1029
0
    }
1030
0
    case CompletionMode::RewriteLine: {
1031
0
      el_deletestr(m_editline, line_info->cursor - line_info->buffer);
1032
0
      el_insertstr(m_editline, completion.GetCompletion().c_str());
1033
0
      break;
1034
0
    }
1035
0
    }
1036
0
    return CC_REDISPLAY;
1037
0
  }
1038
1039
  // If we get a longer match display that first.
1040
0
  std::string longest_prefix = completions.LongestCommonPrefix();
1041
0
  if (!longest_prefix.empty())
1042
0
    longest_prefix =
1043
0
        longest_prefix.substr(request.GetCursorArgumentPrefix().size());
1044
0
  if (!longest_prefix.empty()) {
1045
0
    el_insertstr(m_editline, longest_prefix.c_str());
1046
0
    return CC_REDISPLAY;
1047
0
  }
1048
1049
0
  DisplayCompletions(m_editline, m_output_file, results);
1050
1051
0
  DisplayInput();
1052
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
1053
0
  return CC_REDISPLAY;
1054
0
}
1055
1056
0
unsigned char Editline::ApplyAutosuggestCommand(int ch) {
1057
0
  if (!m_suggestion_callback) {
1058
0
    return CC_REDISPLAY;
1059
0
  }
1060
1061
0
  const LineInfo *line_info = el_line(m_editline);
1062
0
  llvm::StringRef line(line_info->buffer,
1063
0
                       line_info->lastchar - line_info->buffer);
1064
1065
0
  if (llvm::Optional<std::string> to_add = m_suggestion_callback(line))
1066
0
    el_insertstr(m_editline, to_add->c_str());
1067
1068
0
  return CC_REDISPLAY;
1069
0
}
1070
1071
0
unsigned char Editline::TypedCharacter(int ch) {
1072
0
  std::string typed = std::string(1, ch);
1073
0
  el_insertstr(m_editline, typed.c_str());
1074
1075
0
  if (!m_suggestion_callback) {
1076
0
    return CC_REDISPLAY;
1077
0
  }
1078
1079
0
  const LineInfo *line_info = el_line(m_editline);
1080
0
  llvm::StringRef line(line_info->buffer,
1081
0
                       line_info->lastchar - line_info->buffer);
1082
1083
0
  if (llvm::Optional<std::string> to_add = m_suggestion_callback(line)) {
1084
0
    std::string to_add_color = ANSI_FAINT + to_add.getValue() + ANSI_UNFAINT;
1085
0
    fputs(typed.c_str(), m_output_file);
1086
0
    fputs(to_add_color.c_str(), m_output_file);
1087
0
    size_t new_autosuggestion_size = line.size() + to_add->length();
1088
    // Print spaces to hide any remains of a previous longer autosuggestion.
1089
0
    if (new_autosuggestion_size < m_previous_autosuggestion_size) {
1090
0
      size_t spaces_to_print =
1091
0
          m_previous_autosuggestion_size - new_autosuggestion_size;
1092
0
      std::string spaces = std::string(spaces_to_print, ' ');
1093
0
      fputs(spaces.c_str(), m_output_file);
1094
0
    }
1095
0
    m_previous_autosuggestion_size = new_autosuggestion_size;
1096
1097
0
    int editline_cursor_position =
1098
0
        (int)((line_info->cursor - line_info->buffer) + GetPromptWidth());
1099
0
    int editline_cursor_row = editline_cursor_position / m_terminal_width;
1100
0
    int toColumn =
1101
0
        editline_cursor_position - (editline_cursor_row * m_terminal_width);
1102
0
    fprintf(m_output_file, ANSI_SET_COLUMN_N, toColumn);
1103
0
    return CC_REFRESH;
1104
0
  }
1105
1106
0
  return CC_REDISPLAY;
1107
0
}
1108
1109
void Editline::AddFunctionToEditLine(const EditLineCharType *command,
1110
                                     const EditLineCharType *helptext,
1111
112
                                     EditlineCommandCallbackType callbackFn) {
1112
112
  el_wset(m_editline, EL_ADDFN, command, helptext, callbackFn);
1113
112
}
1114
1115
void Editline::SetEditLinePromptCallback(
1116
8
    EditlinePromptCallbackType callbackFn) {
1117
8
  el_set(m_editline, EL_PROMPT, callbackFn);
1118
8
}
1119
1120
8
void Editline::SetGetCharacterFunction(EditlineGetCharCallbackType callbackFn) {
1121
8
  el_wset(m_editline, EL_GETCFN, callbackFn);
1122
8
}
1123
1124
34
void Editline::ConfigureEditor(bool multiline) {
1125
34
  if (m_editline && 
m_multiline_enabled == multiline26
)
1126
26
    return;
1127
8
  m_multiline_enabled = multiline;
1128
1129
8
  if (m_editline) {
1130
    // Disable edit mode to stop the terminal from flushing all input during
1131
    // the call to el_end() since we expect to have multiple editline instances
1132
    // in this program.
1133
0
    el_set(m_editline, EL_EDITMODE, 0);
1134
0
    el_end(m_editline);
1135
0
  }
1136
1137
8
  m_editline =
1138
8
      el_init(m_editor_name.c_str(), m_input_file, m_output_file, m_error_file);
1139
8
  ApplyTerminalSizeChange();
1140
1141
8
  if (m_history_sp && m_history_sp->IsValid()) {
1142
8
    if (!m_history_sp->Load()) {
1143
0
        fputs("Could not load history file\n.", m_output_file);
1144
0
    }
1145
8
    el_wset(m_editline, EL_HIST, history, m_history_sp->GetHistoryPtr());
1146
8
  }
1147
8
  el_set(m_editline, EL_CLIENTDATA, this);
1148
8
  el_set(m_editline, EL_SIGNAL, 0);
1149
8
  el_set(m_editline, EL_EDITOR, "emacs");
1150
1151
851
  SetGetCharacterFunction([](EditLine *editline, EditLineGetCharType *c) {
1152
851
    return Editline::InstanceFor(editline)->GetCharacter(c);
1153
851
  });
1154
1155
40
  SetEditLinePromptCallback([](EditLine *editline) {
1156
40
    return Editline::InstanceFor(editline)->Prompt();
1157
40
  });
1158
1159
  // Commands used for multiline support, registered whether or not they're
1160
  // used
1161
8
  AddFunctionToEditLine(
1162
8
      EditLineConstString("lldb-break-line"),
1163
8
      EditLineConstString("Insert a line break"),
1164
8
      [](EditLine *editline, int ch) {
1165
0
        return Editline::InstanceFor(editline)->BreakLineCommand(ch);
1166
0
      });
1167
1168
8
  AddFunctionToEditLine(
1169
8
      EditLineConstString("lldb-end-or-add-line"),
1170
8
      EditLineConstString("End editing or continue when incomplete"),
1171
8
      [](EditLine *editline, int ch) {
1172
7
        return Editline::InstanceFor(editline)->EndOrAddLineCommand(ch);
1173
7
      });
1174
8
  AddFunctionToEditLine(
1175
8
      EditLineConstString("lldb-delete-next-char"),
1176
8
      EditLineConstString("Delete next character"),
1177
8
      [](EditLine *editline, int ch) {
1178
0
        return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch);
1179
0
      });
1180
8
  AddFunctionToEditLine(
1181
8
      EditLineConstString("lldb-delete-previous-char"),
1182
8
      EditLineConstString("Delete previous character"),
1183
8
      [](EditLine *editline, int ch) {
1184
0
        return Editline::InstanceFor(editline)->DeletePreviousCharCommand(ch);
1185
0
      });
1186
8
  AddFunctionToEditLine(
1187
8
      EditLineConstString("lldb-previous-line"),
1188
8
      EditLineConstString("Move to previous line"),
1189
8
      [](EditLine *editline, int ch) {
1190
0
        return Editline::InstanceFor(editline)->PreviousLineCommand(ch);
1191
0
      });
1192
8
  AddFunctionToEditLine(
1193
8
      EditLineConstString("lldb-next-line"),
1194
8
      EditLineConstString("Move to next line"), [](EditLine *editline, int ch) {
1195
0
        return Editline::InstanceFor(editline)->NextLineCommand(ch);
1196
0
      });
1197
8
  AddFunctionToEditLine(
1198
8
      EditLineConstString("lldb-previous-history"),
1199
8
      EditLineConstString("Move to previous history"),
1200
8
      [](EditLine *editline, int ch) {
1201
0
        return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch);
1202
0
      });
1203
8
  AddFunctionToEditLine(
1204
8
      EditLineConstString("lldb-next-history"),
1205
8
      EditLineConstString("Move to next history"),
1206
8
      [](EditLine *editline, int ch) {
1207
0
        return Editline::InstanceFor(editline)->NextHistoryCommand(ch);
1208
0
      });
1209
8
  AddFunctionToEditLine(
1210
8
      EditLineConstString("lldb-buffer-start"),
1211
8
      EditLineConstString("Move to start of buffer"),
1212
8
      [](EditLine *editline, int ch) {
1213
0
        return Editline::InstanceFor(editline)->BufferStartCommand(ch);
1214
0
      });
1215
8
  AddFunctionToEditLine(
1216
8
      EditLineConstString("lldb-buffer-end"),
1217
8
      EditLineConstString("Move to end of buffer"),
1218
8
      [](EditLine *editline, int ch) {
1219
0
        return Editline::InstanceFor(editline)->BufferEndCommand(ch);
1220
0
      });
1221
8
  AddFunctionToEditLine(
1222
8
      EditLineConstString("lldb-fix-indentation"),
1223
8
      EditLineConstString("Fix line indentation"),
1224
8
      [](EditLine *editline, int ch) {
1225
0
        return Editline::InstanceFor(editline)->FixIndentationCommand(ch);
1226
0
      });
1227
1228
  // Register the complete callback under two names for compatibility with
1229
  // older clients using custom .editrc files (largely because libedit has a
1230
  // bad bug where if you have a bind command that tries to bind to a function
1231
  // name that doesn't exist, it can corrupt the heap and crash your process
1232
  // later.)
1233
8
  EditlineCommandCallbackType complete_callback = [](EditLine *editline,
1234
8
                                                     int ch) {
1235
0
    return Editline::InstanceFor(editline)->TabCommand(ch);
1236
0
  };
1237
8
  AddFunctionToEditLine(EditLineConstString("lldb-complete"),
1238
8
                        EditLineConstString("Invoke completion"),
1239
8
                        complete_callback);
1240
8
  AddFunctionToEditLine(EditLineConstString("lldb_complete"),
1241
8
                        EditLineConstString("Invoke completion"),
1242
8
                        complete_callback);
1243
1244
  // General bindings we don't mind being overridden
1245
8
  if (!multiline) {
1246
6
    el_set(m_editline, EL_BIND, "^r", "em-inc-search-prev",
1247
6
           NULL); // Cycle through backwards search, entering string
1248
1249
6
    if (m_suggestion_callback) {
1250
0
      AddFunctionToEditLine(
1251
0
          EditLineConstString("lldb-apply-complete"),
1252
0
          EditLineConstString("Adopt autocompletion"),
1253
0
          [](EditLine *editline, int ch) {
1254
0
            return Editline::InstanceFor(editline)->ApplyAutosuggestCommand(ch);
1255
0
          });
1256
1257
0
      el_set(m_editline, EL_BIND, "^f", "lldb-apply-complete",
1258
0
             NULL); // Apply a part that is suggested automatically
1259
1260
0
      AddFunctionToEditLine(
1261
0
          EditLineConstString("lldb-typed-character"),
1262
0
          EditLineConstString("Typed character"),
1263
0
          [](EditLine *editline, int ch) {
1264
0
            return Editline::InstanceFor(editline)->TypedCharacter(ch);
1265
0
          });
1266
1267
0
      char bind_key[2] = {0, 0};
1268
0
      llvm::StringRef ascii_chars =
1269
0
          "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXZY1234567890!\"#$%"
1270
0
          "&'()*+,./:;<=>?@[]_`{|}~ ";
1271
0
      for (char c : ascii_chars) {
1272
0
        bind_key[0] = c;
1273
0
        el_set(m_editline, EL_BIND, bind_key, "lldb-typed-character", NULL);
1274
0
      }
1275
0
      el_set(m_editline, EL_BIND, "\\-", "lldb-typed-character", NULL);
1276
0
      el_set(m_editline, EL_BIND, "\\^", "lldb-typed-character", NULL);
1277
0
      el_set(m_editline, EL_BIND, "\\\\", "lldb-typed-character", NULL);
1278
0
    }
1279
6
  }
1280
1281
8
  el_set(m_editline, EL_BIND, "^w", "ed-delete-prev-word",
1282
8
         NULL); // Delete previous word, behave like bash in emacs mode
1283
8
  el_set(m_editline, EL_BIND, "\t", "lldb-complete",
1284
8
         NULL); // Bind TAB to auto complete
1285
1286
  // Allow ctrl-left-arrow and ctrl-right-arrow for navigation, behave like
1287
  // bash in emacs mode.
1288
8
  el_set(m_editline, EL_BIND, ESCAPE "[1;5C", "em-next-word", NULL);
1289
8
  el_set(m_editline, EL_BIND, ESCAPE "[1;5D", "ed-prev-word", NULL);
1290
8
  el_set(m_editline, EL_BIND, ESCAPE "[5C", "em-next-word", NULL);
1291
8
  el_set(m_editline, EL_BIND, ESCAPE "[5D", "ed-prev-word", NULL);
1292
8
  el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[C", "em-next-word", NULL);
1293
8
  el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[D", "ed-prev-word", NULL);
1294
1295
  // Allow user-specific customization prior to registering bindings we
1296
  // absolutely require
1297
8
  el_source(m_editline, nullptr);
1298
1299
  // Register an internal binding that external developers shouldn't use
1300
8
  AddFunctionToEditLine(
1301
8
      EditLineConstString("lldb-revert-line"),
1302
8
      EditLineConstString("Revert line to saved state"),
1303
8
      [](EditLine *editline, int ch) {
1304
7
        return Editline::InstanceFor(editline)->RevertLineCommand(ch);
1305
7
      });
1306
1307
  // Register keys that perform auto-indent correction
1308
8
  if (m_fix_indentation_callback && 
m_fix_indentation_callback_chars0
) {
1309
0
    char bind_key[2] = {0, 0};
1310
0
    const char *indent_chars = m_fix_indentation_callback_chars;
1311
0
    while (*indent_chars) {
1312
0
      bind_key[0] = *indent_chars;
1313
0
      el_set(m_editline, EL_BIND, bind_key, "lldb-fix-indentation", NULL);
1314
0
      ++indent_chars;
1315
0
    }
1316
0
  }
1317
1318
  // Multi-line editor bindings
1319
8
  if (multiline) {
1320
2
    el_set(m_editline, EL_BIND, "\n", "lldb-end-or-add-line", NULL);
1321
2
    el_set(m_editline, EL_BIND, "\r", "lldb-end-or-add-line", NULL);
1322
2
    el_set(m_editline, EL_BIND, ESCAPE "\n", "lldb-break-line", NULL);
1323
2
    el_set(m_editline, EL_BIND, ESCAPE "\r", "lldb-break-line", NULL);
1324
2
    el_set(m_editline, EL_BIND, "^p", "lldb-previous-line", NULL);
1325
2
    el_set(m_editline, EL_BIND, "^n", "lldb-next-line", NULL);
1326
2
    el_set(m_editline, EL_BIND, "^?", "lldb-delete-previous-char", NULL);
1327
2
    el_set(m_editline, EL_BIND, "^d", "lldb-delete-next-char", NULL);
1328
2
    el_set(m_editline, EL_BIND, ESCAPE "[3~", "lldb-delete-next-char", NULL);
1329
2
    el_set(m_editline, EL_BIND, ESCAPE "[\\^", "lldb-revert-line", NULL);
1330
1331
    // Editor-specific bindings
1332
2
    if (IsEmacs()) {
1333
2
      el_set(m_editline, EL_BIND, ESCAPE "<", "lldb-buffer-start", NULL);
1334
2
      el_set(m_editline, EL_BIND, ESCAPE ">", "lldb-buffer-end", NULL);
1335
2
      el_set(m_editline, EL_BIND, ESCAPE "[A", "lldb-previous-line", NULL);
1336
2
      el_set(m_editline, EL_BIND, ESCAPE "[B", "lldb-next-line", NULL);
1337
2
      el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[A", "lldb-previous-history",
1338
2
             NULL);
1339
2
      el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[B", "lldb-next-history",
1340
2
             NULL);
1341
2
      el_set(m_editline, EL_BIND, ESCAPE "[1;3A", "lldb-previous-history",
1342
2
             NULL);
1343
2
      el_set(m_editline, EL_BIND, ESCAPE "[1;3B", "lldb-next-history", NULL);
1344
2
    } else {
1345
0
      el_set(m_editline, EL_BIND, "^H", "lldb-delete-previous-char", NULL);
1346
1347
0
      el_set(m_editline, EL_BIND, "-a", ESCAPE "[A", "lldb-previous-line",
1348
0
             NULL);
1349
0
      el_set(m_editline, EL_BIND, "-a", ESCAPE "[B", "lldb-next-line", NULL);
1350
0
      el_set(m_editline, EL_BIND, "-a", "x", "lldb-delete-next-char", NULL);
1351
0
      el_set(m_editline, EL_BIND, "-a", "^H", "lldb-delete-previous-char",
1352
0
             NULL);
1353
0
      el_set(m_editline, EL_BIND, "-a", "^?", "lldb-delete-previous-char",
1354
0
             NULL);
1355
1356
      // Escape is absorbed exiting edit mode, so re-register important
1357
      // sequences without the prefix
1358
0
      el_set(m_editline, EL_BIND, "-a", "[A", "lldb-previous-line", NULL);
1359
0
      el_set(m_editline, EL_BIND, "-a", "[B", "lldb-next-line", NULL);
1360
0
      el_set(m_editline, EL_BIND, "-a", "[\\^", "lldb-revert-line", NULL);
1361
0
    }
1362
2
  }
1363
8
}
1364
1365
// Editline public methods
1366
1367
905
Editline *Editline::InstanceFor(EditLine *editline) {
1368
905
  Editline *editor;
1369
905
  el_get(editline, EL_CLIENTDATA, &editor);
1370
905
  return editor;
1371
905
}
1372
1373
Editline::Editline(const char *editline_name, FILE *input_file,
1374
                   FILE *output_file, FILE *error_file, bool color_prompts)
1375
    : m_editor_status(EditorStatus::Complete), m_color_prompts(color_prompts),
1376
      m_input_file(input_file), m_output_file(output_file),
1377
8
      m_error_file(error_file), m_input_connection(fileno(input_file), false) {
1378
  // Get a shared history instance
1379
8
  m_editor_name = (editline_name == nullptr) ? 
"lldb-tmp"0
: editline_name;
1380
8
  m_history_sp = EditlineHistory::GetHistory(m_editor_name);
1381
1382
8
#ifdef USE_SETUPTERM_WORKAROUND
1383
8
  if (m_output_file) {
1384
8
    const int term_fd = fileno(m_output_file);
1385
8
    if (term_fd != -1) {
1386
8
      static std::mutex *g_init_terminal_fds_mutex_ptr = nullptr;
1387
8
      static std::set<int> *g_init_terminal_fds_ptr = nullptr;
1388
8
      static llvm::once_flag g_once_flag;
1389
8
      llvm::call_once(g_once_flag, [&]() {
1390
7
        g_init_terminal_fds_mutex_ptr =
1391
7
            new std::mutex(); // NOTE: Leak to avoid C++ destructor chain issues
1392
7
        g_init_terminal_fds_ptr = new std::set<int>(); // NOTE: Leak to avoid
1393
                                                       // C++ destructor chain
1394
                                                       // issues
1395
7
      });
1396
1397
      // We must make sure to initialize the terminal a given file descriptor
1398
      // only once. If we do this multiple times, we start leaking memory.
1399
8
      std::lock_guard<std::mutex> guard(*g_init_terminal_fds_mutex_ptr);
1400
8
      if (g_init_terminal_fds_ptr->find(term_fd) ==
1401
8
          g_init_terminal_fds_ptr->end()) {
1402
7
        g_init_terminal_fds_ptr->insert(term_fd);
1403
7
        setupterm((char *)0, term_fd, (int *)0);
1404
7
      }
1405
8
    }
1406
8
  }
1407
8
#endif
1408
8
}
1409
1410
8
Editline::~Editline() {
1411
8
  if (m_editline) {
1412
    // Disable edit mode to stop the terminal from flushing all input during
1413
    // the call to el_end() since we expect to have multiple editline instances
1414
    // in this program.
1415
8
    el_set(m_editline, EL_EDITMODE, 0);
1416
8
    el_end(m_editline);
1417
8
    m_editline = nullptr;
1418
8
  }
1419
1420
  // EditlineHistory objects are sometimes shared between multiple Editline
1421
  // instances with the same program name. So just release our shared pointer
1422
  // and if we are the last owner, it will save the history to the history save
1423
  // file automatically.
1424
8
  m_history_sp.reset();
1425
8
}
1426
1427
8
void Editline::SetPrompt(const char *prompt) {
1428
8
  m_set_prompt = prompt == nullptr ? 
""0
: prompt;
1429
8
}
1430
1431
6
void Editline::SetContinuationPrompt(const char *continuation_prompt) {
1432
6
  m_set_continuation_prompt =
1433
6
      continuation_prompt == nullptr ? "" : 
continuation_prompt0
;
1434
6
}
1435
1436
0
void Editline::TerminalSizeChanged() { m_terminal_size_has_changed = 1; }
1437
1438
8
void Editline::ApplyTerminalSizeChange() {
1439
8
  if (!m_editline)
1440
0
    return;
1441
1442
8
  m_terminal_size_has_changed = 0;
1443
8
  el_resize(m_editline);
1444
8
  int columns;
1445
  // This function is documenting as taking (const char *, void *) for the
1446
  // vararg part, but in reality in was consuming arguments until the first
1447
  // null pointer. This was fixed in libedit in April 2019
1448
  // <http://mail-index.netbsd.org/source-changes/2019/04/26/msg105454.html>,
1449
  // but we're keeping the workaround until a version with that fix is more
1450
  // widely available.
1451
8
  if (el_get(m_editline, EL_GETTC, "co", &columns, nullptr) == 0) {
1452
8
    m_terminal_width = columns;
1453
8
    if (m_current_line_rows != -1) {
1454
0
      const LineInfoW *info = el_wline(m_editline);
1455
0
      int lineLength =
1456
0
          (int)((info->lastchar - info->buffer) + GetPromptWidth());
1457
0
      m_current_line_rows = (lineLength / columns) + 1;
1458
0
    }
1459
8
  } else {
1460
0
    m_terminal_width = INT_MAX;
1461
0
    m_current_line_rows = 1;
1462
0
  }
1463
8
}
1464
1465
0
const char *Editline::GetPrompt() { return m_set_prompt.c_str(); }
1466
1467
0
uint32_t Editline::GetCurrentLine() { return m_current_line_index; }
1468
1469
0
bool Editline::Interrupt() {
1470
0
  bool result = true;
1471
0
  std::lock_guard<std::mutex> guard(m_output_mutex);
1472
0
  if (m_editor_status == EditorStatus::Editing) {
1473
0
    fprintf(m_output_file, "^C\n");
1474
0
    result = m_input_connection.InterruptRead();
1475
0
  }
1476
0
  m_editor_status = EditorStatus::Interrupted;
1477
0
  return result;
1478
0
}
1479
1480
12
bool Editline::Cancel() {
1481
12
  bool result = true;
1482
12
  std::lock_guard<std::mutex> guard(m_output_mutex);
1483
12
  if (m_editor_status == EditorStatus::Editing) {
1484
0
    MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1485
0
    fprintf(m_output_file, ANSI_CLEAR_BELOW);
1486
0
    result = m_input_connection.InterruptRead();
1487
0
  }
1488
12
  m_editor_status = EditorStatus::Interrupted;
1489
12
  return result;
1490
12
}
1491
1492
32
bool Editline::GetLine(std::string &line, bool &interrupted) {
1493
32
  ConfigureEditor(false);
1494
32
  m_input_lines = std::vector<EditLineStringType>();
1495
32
  m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1496
1497
32
  std::lock_guard<std::mutex> guard(m_output_mutex);
1498
1499
32
  lldbassert(m_editor_status != EditorStatus::Editing);
1500
32
  if (m_editor_status == EditorStatus::Interrupted) {
1501
6
    m_editor_status = EditorStatus::Complete;
1502
6
    interrupted = true;
1503
6
    return true;
1504
6
  }
1505
1506
26
  SetCurrentLine(0);
1507
26
  m_in_history = false;
1508
26
  m_editor_status = EditorStatus::Editing;
1509
26
  m_revert_cursor_index = -1;
1510
1511
26
  int count;
1512
26
  auto input = el_wgets(m_editline, &count);
1513
1514
26
  interrupted = m_editor_status == EditorStatus::Interrupted;
1515
26
  if (!interrupted) {
1516
26
    if (input == nullptr) {
1517
0
      fprintf(m_output_file, "\n");
1518
0
      m_editor_status = EditorStatus::EndOfInput;
1519
26
    } else {
1520
26
      m_history_sp->Enter(input);
1521
26
#if LLDB_EDITLINE_USE_WCHAR
1522
26
      line = m_utf8conv.to_bytes(SplitLines(input)[0]);
1523
#else
1524
      line = SplitLines(input)[0];
1525
#endif
1526
26
      m_editor_status = EditorStatus::Complete;
1527
26
    }
1528
26
  }
1529
26
  return m_editor_status != EditorStatus::EndOfInput;
1530
32
}
1531
1532
bool Editline::GetLines(int first_line_number, StringList &lines,
1533
2
                        bool &interrupted) {
1534
2
  ConfigureEditor(true);
1535
1536
  // Print the initial input lines, then move the cursor back up to the start
1537
  // of input
1538
2
  SetBaseLineNumber(first_line_number);
1539
2
  m_input_lines = std::vector<EditLineStringType>();
1540
2
  m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1541
1542
2
  std::lock_guard<std::mutex> guard(m_output_mutex);
1543
  // Begin the line editing loop
1544
2
  DisplayInput();
1545
2
  SetCurrentLine(0);
1546
2
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::BlockStart);
1547
2
  m_editor_status = EditorStatus::Editing;
1548
2
  m_in_history = false;
1549
1550
2
  m_revert_cursor_index = -1;
1551
9
  while (m_editor_status == EditorStatus::Editing) {
1552
7
    int count;
1553
7
    m_current_line_rows = -1;
1554
7
    el_wpush(m_editline, EditLineConstString(
1555
7
                             "\x1b[^")); // Revert to the existing line content
1556
7
    el_wgets(m_editline, &count);
1557
7
  }
1558
1559
2
  interrupted = m_editor_status == EditorStatus::Interrupted;
1560
2
  if (!interrupted) {
1561
    // Save the completed entry in history before returning. Don't save empty
1562
    // input as that just clutters the command history.
1563
2
    if (!m_input_lines.empty())
1564
2
      m_history_sp->Enter(CombineLines(m_input_lines).c_str());
1565
1566
2
    lines = GetInputAsStringList();
1567
2
  }
1568
2
  return m_editor_status != EditorStatus::EndOfInput;
1569
2
}
1570
1571
1
void Editline::PrintAsync(Stream *stream, const char *s, size_t len) {
1572
1
  std::lock_guard<std::mutex> guard(m_output_mutex);
1573
1
  if (m_editor_status == EditorStatus::Editing) {
1574
1
    MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1575
1
    fprintf(m_output_file, ANSI_CLEAR_BELOW);
1576
1
  }
1577
1
  stream->Write(s, len);
1578
1
  stream->Flush();
1579
1
  if (m_editor_status == EditorStatus::Editing) {
1580
1
    DisplayInput();
1581
1
    MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
1582
1
  }
1583
1
}
1584
1585
851
bool Editline::CompleteCharacter(char ch, EditLineGetCharType &out) {
1586
#if !LLDB_EDITLINE_USE_WCHAR
1587
  if (ch == (char)EOF)
1588
    return false;
1589
1590
  out = (unsigned char)ch;
1591
  return true;
1592
#else
1593
851
  std::codecvt_utf8<wchar_t> cvt;
1594
851
  llvm::SmallString<4> input;
1595
851
  for (;;) {
1596
851
    const char *from_next;
1597
851
    wchar_t *to_next;
1598
851
    std::mbstate_t state = std::mbstate_t();
1599
851
    input.push_back(ch);
1600
851
    switch (cvt.in(state, input.begin(), input.end(), from_next, &out, &out + 1,
1601
851
                   to_next)) {
1602
851
    case std::codecvt_base::ok:
1603
851
      return out != (int)WEOF;
1604
1605
0
    case std::codecvt_base::error:
1606
0
    case std::codecvt_base::noconv:
1607
0
      return false;
1608
1609
0
    case std::codecvt_base::partial:
1610
0
      lldb::ConnectionStatus status;
1611
0
      size_t read_count = m_input_connection.Read(
1612
0
          &ch, 1, std::chrono::seconds(0), status, nullptr);
1613
0
      if (read_count == 0)
1614
0
        return false;
1615
0
      break;
1616
851
    }
1617
851
  }
1618
851
#endif
1619
851
}