text_editing_action_target.dart 53.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:math' as math;
import 'dart:ui' show TextAffinity, TextPosition;

import 'package:characters/characters.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart'
    show Clipboard, ClipboardData, TextLayoutMetrics, TextRange;

import 'editable_text.dart';

/// The recipient of a [TextEditingAction].
///
/// TextEditingActions will only be enabled when an implementer of this class is
/// focused.
///
/// See also:
///
///   * [EditableTextState], which implements this and is the most typical
///     target of a TextEditingAction.
abstract class TextEditingActionTarget {
  /// Whether the characters in the field are obscured from the user.
  ///
  /// When true, the entire contents of the field are treated as one word.
  bool get obscureText;

  /// Whether the field currently in a read-only state.
  ///
  /// When true, [textEditingValue]'s text may not be modified, but its selection can be.
  bool get readOnly;

  /// Whether the [textEditingValue]'s selection can be modified.
  bool get selectionEnabled;

  /// Provides information about the text that is the target of this action.
  ///
  /// See also:
  ///
  /// * [EditableTextState.renderEditable], which overrides this.
  TextLayoutMetrics get textLayoutMetrics;

  /// The [TextEditingValue] expressed in this field.
  TextEditingValue get textEditingValue;

  // Holds the last cursor location the user selected in the case the user tries
  // to select vertically past the end or beginning of the field. If they do,
  // then we need to keep the old cursor location so that we can go back to it
  // if they change their minds. Only used for moving selection up and down in a
  // multiline text field when selecting using the keyboard.
  int _cursorResetLocation = -1;

  // Whether we should reset the location of the cursor in the case the user
  // tries to select vertically past the end or beginning of the field. If they
  // do, then we need to keep the old cursor location so that we can go back to
  // it if they change their minds. Only used for resetting selection up and
  // down in a multiline text field when selecting using the keyboard.
  bool _wasSelectingVerticallyWithKeyboard = false;

  /// Called when assuming that the text layout is in sync with
  /// [textEditingValue].
  ///
  /// Can be overridden to assert that this is a valid assumption.
  void debugAssertLayoutUpToDate();

  /// Returns the index into the string of the next character boundary after the
  /// given index.
  ///
  /// The character boundary is determined by the characters package, so
  /// surrogate pairs and extended grapheme clusters are considered.
  ///
  /// The index must be between 0 and string.length, inclusive. If given
  /// string.length, string.length is returned.
  ///
  /// Setting includeWhitespace to false will only return the index of non-space
  /// characters.
  @visibleForTesting
  static int nextCharacter(int index, String string, [bool includeWhitespace = true]) {
    assert(index >= 0 && index <= string.length);
    if (index == string.length) {
      return string.length;
    }

    final CharacterRange range = CharacterRange.at(string, 0, index);
    // If index is not on a character boundary, return the next character
    // boundary.
    if (range.current.length != index) {
      return range.current.length;
    }

    range.expandNext();
    if (!includeWhitespace) {
      range.expandWhile((String character) {
        return TextLayoutMetrics.isWhitespace(character.codeUnitAt(0));
      });
    }
    return range.current.length;
  }

  /// Returns the index into the string of the previous character boundary
  /// before the given index.
  ///
  /// The character boundary is determined by the characters package, so
  /// surrogate pairs and extended grapheme clusters are considered.
  ///
  /// The index must be between 0 and string.length, inclusive. If index is 0,
  /// 0 will be returned.
  ///
  /// Setting includeWhitespace to false will only return the index of non-space
  /// characters.
  @visibleForTesting
  static int previousCharacter(int index, String string, [bool includeWhitespace = true]) {
    assert(index >= 0 && index <= string.length);
    if (index == 0) {
      return 0;
    }

    final CharacterRange range = CharacterRange.at(string, 0, index);
    // If index is not on a character boundary, return the previous character
    // boundary.
    if (range.current.length != index) {
      range.dropLast();
      return range.current.length;
    }

    range.dropLast();
    if (!includeWhitespace) {
      while (range.currentCharacters.isNotEmpty
          && TextLayoutMetrics.isWhitespace(range.charactersAfter.first.codeUnitAt(0))) {
        range.dropLast();
      }
    }
    return range.current.length;
  }

  /// {@template flutter.widgets.TextEditingActionTarget.setSelection}
  /// Called to update the [TextSelection] in the current [TextEditingValue].
  /// {@endtemplate}
  void setSelection(TextSelection nextSelection, SelectionChangedCause cause) {
    if (nextSelection == textEditingValue.selection) {
      return;
    }
    setTextEditingValue(
      textEditingValue.copyWith(selection: nextSelection),
      cause,
    );
  }

  /// {@template flutter.widgets.TextEditingActionTarget.setTextEditingValue}
  /// Called to update the current [TextEditingValue].
  /// {@endtemplate}
  void setTextEditingValue(TextEditingValue newValue, SelectionChangedCause cause);

  // Extend the current selection to the end of the field.
  //
  // If selectionEnabled is false, keeps the selection collapsed and moves it to
  // the end.
  //
  // See also:
  //
  //   * _extendSelectionToStart
  void _extendSelectionToEnd(SelectionChangedCause cause) {
    if (textEditingValue.selection.extentOffset == textEditingValue.text.length) {
      return;
    }

    final TextSelection nextSelection = textEditingValue.selection.copyWith(
      extentOffset: textEditingValue.text.length,
    );
    return setSelection(nextSelection, cause);
  }

  // Extend the current selection to the start of the field.
  //
  // If selectionEnabled is false, keeps the selection collapsed and moves it to
  // the start.
  //
  // The given [SelectionChangedCause] indicates the cause of this change and
  // will be passed to [setSelection].
  //
  // See also:
  //
  //   * _extendSelectionToEnd
  void _extendSelectionToStart(SelectionChangedCause cause) {
    if (!selectionEnabled) {
      return moveSelectionToStart(cause);
    }

    setSelection(textEditingValue.selection.extendTo(const TextPosition(
      offset: 0,
      affinity: TextAffinity.upstream,
    )), cause);
  }

  // Return the offset at the start of the nearest word to the left of the
  // given offset.
  int _getLeftByWord(int offset, [bool includeWhitespace = true]) {
    // If the offset is already all the way left, there is nothing to do.
    if (offset <= 0) {
      return offset;
    }

    // If we can just return the start of the text without checking for a word.
    if (offset == 1) {
      return 0;
    }

    final int startPoint = previousCharacter(
        offset, textEditingValue.text, includeWhitespace);
    final TextRange word =
        textLayoutMetrics.getWordBoundary(TextPosition(offset: startPoint, affinity: textEditingValue.selection.affinity));
    return word.start;
  }

  /// Return the offset at the end of the nearest word to the right of the given
  /// offset.
  int _getRightByWord(int offset, [bool includeWhitespace = true]) {
    // If the selection is already all the way right, there is nothing to do.
    if (offset == textEditingValue.text.length) {
      return offset;
    }

    // If we can just return the end of the text without checking for a word.
    if (offset == textEditingValue.text.length - 1 || offset == textEditingValue.text.length) {
      return textEditingValue.text.length;
    }

    final int startPoint = includeWhitespace ||
            !TextLayoutMetrics.isWhitespace(textEditingValue.text.codeUnitAt(offset))
        ? offset
        : nextCharacter(offset, textEditingValue.text, includeWhitespace);
    final TextRange nextWord =
        textLayoutMetrics.getWordBoundary(TextPosition(offset: startPoint, affinity: textEditingValue.selection.affinity));
    return nextWord.end;
  }

  // Deletes the current non-empty selection.
  //
  // If the selection is currently non-empty, this method deletes the selected
  // text. Otherwise this method does nothing.
  TextEditingValue _deleteNonEmptySelection() {
    assert(textEditingValue.selection.isValid);
    assert(!textEditingValue.selection.isCollapsed);

    final String textBefore = textEditingValue.selection.textBefore(textEditingValue.text);
    final String textAfter = textEditingValue.selection.textAfter(textEditingValue.text);
    final TextSelection newSelection = TextSelection.collapsed(
      offset: textEditingValue.selection.start,
      affinity: textEditingValue.selection.affinity,
    );
    final TextRange newComposingRange = !textEditingValue.composing.isValid || textEditingValue.composing.isCollapsed
      ? TextRange.empty
      : TextRange(
        start: textEditingValue.composing.start - (textEditingValue.composing.start - textEditingValue.selection.start).clamp(0, textEditingValue.selection.end - textEditingValue.selection.start),
        end: textEditingValue.composing.end - (textEditingValue.composing.end - textEditingValue.selection.start).clamp(0, textEditingValue.selection.end - textEditingValue.selection.start),
      );

    return TextEditingValue(
      text: textBefore + textAfter,
      selection: newSelection,
      composing: newComposingRange,
    );
  }

  /// Returns a new TextEditingValue representing a deletion from the current
  /// [selection] to the given index, inclusively.
  ///
  /// If the selection is not collapsed, deletes the selection regardless of the
  /// given index.
  ///
  /// The composing region, if any, will also be adjusted to remove the deleted
  /// characters.
  TextEditingValue _deleteTo(TextPosition position) {
    assert(textEditingValue.selection != null);

    if (!textEditingValue.selection.isValid) {
      return textEditingValue;
    }
    if (!textEditingValue.selection.isCollapsed) {
      return _deleteNonEmptySelection();
    }
    if (position.offset == textEditingValue.selection.extentOffset) {
      return textEditingValue;
    }

    final TextRange deletion = TextRange(
      start: math.min(position.offset, textEditingValue.selection.extentOffset),
      end: math.max(position.offset, textEditingValue.selection.extentOffset),
    );
    final String deleted = deletion.textInside(textEditingValue.text);
    if (deletion.textInside(textEditingValue.text).isEmpty) {
      return textEditingValue;
    }

    final int charactersDeletedBeforeComposingStart =
        (textEditingValue.composing.start - deletion.start).clamp(0, deleted.length);
    final int charactersDeletedBeforeComposingEnd =
        (textEditingValue.composing.end - deletion.start).clamp(0, deleted.length);
    final TextRange nextComposingRange = !textEditingValue.composing.isValid || textEditingValue.composing.isCollapsed
      ? TextRange.empty
      : TextRange(
        start: textEditingValue.composing.start - charactersDeletedBeforeComposingStart,
        end: textEditingValue.composing.end - charactersDeletedBeforeComposingEnd,
      );

    return TextEditingValue(
      text: deletion.textBefore(textEditingValue.text) + deletion.textAfter(textEditingValue.text),
      selection: TextSelection.collapsed(
        offset: deletion.start,
        affinity: position.affinity,
      ),
      composing: nextComposingRange,
    );
  }

  /// Deletes backwards from the current selection.
  ///
  /// If the selection is collapsed, deletes a single character before the
  /// cursor.
  ///
  /// If the selection is not collapsed, deletes the selection.
  ///
325
  /// If [readOnly] is true or the selection is invalid, does nothing.
326 327 328 329 330 331 332 333 334 335 336 337 338
  ///
  /// {@template flutter.widgets.TextEditingActionTarget.cause}
  /// The given [SelectionChangedCause] indicates the cause of this change and
  /// will be passed to [setSelection].
  /// {@endtemplate}
  ///
  /// See also:
  ///
  ///   * [deleteForward], which is same but in the opposite direction.
  void delete(SelectionChangedCause cause) {
    if (readOnly) {
      return;
    }
339 340 341
    if (!textEditingValue.selection.isValid) {
      return;
    }
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361

    // `delete` does not depend on the text layout, and the boundary analysis is
    // done using the `previousCharacter` method instead of ICU, we can keep
    // deleting without having to layout the text. For this reason, we can
    // directly delete the character before the caret in the controller.
    final String textBefore = textEditingValue.selection.textBefore(textEditingValue.text);
    final int characterBoundary = previousCharacter(
      textBefore.length,
      textBefore,
    );
    final TextPosition position = TextPosition(offset: characterBoundary);
    setTextEditingValue(_deleteTo(position), cause);
  }

  /// Deletes a word backwards from the current selection.
  ///
  /// If the selection is collapsed, deletes a word before the cursor.
  ///
  /// If the selection is not collapsed, deletes the selection.
  ///
362
  /// If [readOnly] is true or the selection is invalid, does nothing.
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
  ///
  /// If [obscureText] is true, it treats the whole text content as a single
  /// word.
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// {@template flutter.widgets.TextEditingActionTarget.whiteSpace}
  /// By default, includeWhitespace is set to true, meaning that whitespace can
  /// be considered a word in itself.  If set to false, the selection will be
  /// extended past any whitespace and the first word following the whitespace.
  /// {@endtemplate}
  ///
  /// See also:
  ///
  ///   * [deleteForwardByWord], which is same but in the opposite direction.
  void deleteByWord(SelectionChangedCause cause,
      [bool includeWhitespace = true]) {
    if (readOnly) {
      return;
    }
383 384 385
    if (!textEditingValue.selection.isValid) {
      return;
    }
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

    if (obscureText) {
      // When the text is obscured, the whole thing is treated as one big line.
      return deleteToStart(cause);
    }

    final String textBefore = textEditingValue.selection.textBefore(textEditingValue.text);
    final int characterBoundary =
        _getLeftByWord(textBefore.length, includeWhitespace);
    final TextEditingValue nextValue = _deleteTo(TextPosition(offset: characterBoundary));

    setTextEditingValue(nextValue, cause);
  }

  /// Deletes a line backwards from the current selection.
  ///
  /// If the selection is collapsed, deletes a line before the cursor.
  ///
  /// If the selection is not collapsed, deletes the selection.
  ///
  /// If [obscureText] is true, it treats the whole text content as
  /// a single word.
  ///
409
  /// If [readOnly] is true or the selection is invalid, does nothing.
410 411 412 413 414 415 416 417 418 419
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [deleteForwardByLine], which is same but in the opposite direction.
  void deleteByLine(SelectionChangedCause cause) {
    if (readOnly) {
      return;
    }
420 421 422
    if (!textEditingValue.selection.isValid) {
      return;
    }
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450

    // When there is a line break, line delete shouldn't do anything
    final String textBefore = textEditingValue.selection.textBefore(textEditingValue.text);
    final bool isPreviousCharacterBreakLine =
        textBefore.codeUnitAt(textBefore.length - 1) == 0x0A;
    if (isPreviousCharacterBreakLine) {
      return;
    }

    // When the text is obscured, the whole thing is treated as one big line.
    if (obscureText) {
      return deleteToStart(cause);
    }

    final TextSelection line = textLayoutMetrics.getLineAtOffset(
      TextPosition(offset: textBefore.length - 1),
    );

    setTextEditingValue(_deleteTo(TextPosition(offset: line.start)), cause);
  }

  /// Deletes in the forward direction.
  ///
  /// If the selection is collapsed, deletes a single character after the
  /// cursor.
  ///
  /// If the selection is not collapsed, deletes the selection.
  ///
451
  /// If [readOnly] is true or the selection is invalid, does nothing.
452 453 454 455 456 457 458 459 460 461
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [delete], which is the same but in the opposite direction.
  void deleteForward(SelectionChangedCause cause) {
    if (readOnly) {
      return;
    }
462 463 464
    if (!textEditingValue.selection.isValid) {
      return;
    }
465 466 467 468 469 470 471 472 473 474 475 476

    final String textAfter = textEditingValue.selection.textAfter(textEditingValue.text);
    final int characterBoundary = nextCharacter(0, textAfter);
    setTextEditingValue(_deleteTo(TextPosition(offset: textEditingValue.selection.end + characterBoundary)), cause);
  }

  /// Deletes a word in the forward direction from the current selection.
  ///
  /// If the selection is collapsed, deletes a word after the cursor.
  ///
  /// If the selection is not collapsed, deletes the selection.
  ///
477
  /// If [readOnly] is true or the selection is invalid, does nothing.
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
  ///
  /// If [obscureText] is true, it treats the whole text content as
  /// a single word.
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.whiteSpace}
  ///
  /// See also:
  ///
  ///   * [deleteByWord], which is same but in the opposite direction.
  void deleteForwardByWord(SelectionChangedCause cause,
      [bool includeWhitespace = true]) {
    if (readOnly) {
      return;
    }
494 495 496
    if (!textEditingValue.selection.isValid) {
      return;
    }
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515

    if (obscureText) {
      // When the text is obscured, the whole thing is treated as one big word.
      return deleteToEnd(cause);
    }

    final String textBefore = textEditingValue.selection.textBefore(textEditingValue.text);
    final int characterBoundary = _getRightByWord(textBefore.length, includeWhitespace);
    final TextEditingValue nextValue = _deleteTo(TextPosition(offset: characterBoundary));

    setTextEditingValue(nextValue, cause);
  }

  /// Deletes a line in the forward direction from the current selection.
  ///
  /// If the selection is collapsed, deletes a line after the cursor.
  ///
  /// If the selection is not collapsed, deletes the selection.
  ///
516
  /// If [readOnly] is true or the selection is invalid, does nothing.
517 518 519 520 521 522 523 524 525 526 527 528 529
  ///
  /// If [obscureText] is true, it treats the whole text content as
  /// a single word.
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [deleteByLine], which is same but in the opposite direction.
  void deleteForwardByLine(SelectionChangedCause cause) {
    if (readOnly) {
      return;
    }
530 531 532
    if (!textEditingValue.selection.isValid) {
      return;
    }
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

    if (obscureText) {
      // When the text is obscured, the whole thing is treated as one big line.
      return deleteToEnd(cause);
    }


    // When there is a line break, it shouldn't do anything.
    final String textAfter = textEditingValue.selection.textAfter(textEditingValue.text);
    final bool isNextCharacterBreakLine = textAfter.codeUnitAt(0) == 0x0A;
    if (isNextCharacterBreakLine) {
      return;
    }

    final String textBefore = textEditingValue.selection.textBefore(textEditingValue.text);
    final TextSelection line = textLayoutMetrics.getLineAtOffset(
      TextPosition(offset: textBefore.length),
    );

    setTextEditingValue(_deleteTo(TextPosition(offset: line.end)), cause);
  }

  /// Deletes the from the current collapsed selection to the end of the field.
  ///
  /// The given SelectionChangedCause indicates the cause of this change and
  /// will be passed to setSelection.
  ///
560 561
  /// If [readOnly] is true or the selection is invalid, does nothing.
  ///
562 563 564 565
  /// See also:
  ///   * [deleteToStart]
  void deleteToEnd(SelectionChangedCause cause) {
    assert(textEditingValue.selection.isCollapsed);
566 567 568 569 570 571
    if (readOnly) {
      return;
    }
    if (!textEditingValue.selection.isValid) {
      return;
    }
572 573 574 575 576 577 578 579 580

    setTextEditingValue(_deleteTo(TextPosition(offset: textEditingValue.text.length)), cause);
  }

  /// Deletes the from the current collapsed selection to the start of the field.
  ///
  /// The given SelectionChangedCause indicates the cause of this change and
  /// will be passed to setSelection.
  ///
581 582
  /// If [readOnly] is true or the selection is invalid, does nothing.
  ///
583 584 585 586
  /// See also:
  ///   * [deleteToEnd]
  void deleteToStart(SelectionChangedCause cause) {
    assert(textEditingValue.selection.isCollapsed);
587 588 589 590 591 592
    if (readOnly) {
      return;
    }
    if (!textEditingValue.selection.isValid) {
      return;
    }
593 594 595 596 597 598 599 600 601 602 603 604 605

    setTextEditingValue(_deleteTo(const TextPosition(offset: 0)), cause);
  }

  /// Expand the current selection to the end of the field.
  ///
  /// The selection will never shrink. The [TextSelection.extentOffset] will
  // always be at the end of the field, regardless of the original order of
  /// [TextSelection.baseOffset] and [TextSelection.extentOffset].
  ///
  /// If [selectionEnabled] is false, keeps the selection collapsed and moves it
  /// to the end.
  ///
606 607
  /// If the selection is invalid, does nothing.
  ///
608 609 610 611 612 613
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [expandSelectionToStart], which is same but in the opposite direction.
  void expandSelectionToEnd(SelectionChangedCause cause) {
614 615 616
    if (!textEditingValue.selection.isValid) {
      return;
    }
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    if (!selectionEnabled) {
      return moveSelectionToEnd(cause);
    }

    final TextPosition nextPosition = TextPosition(
      offset: textEditingValue.text.length,
    );
    setSelection(textEditingValue.selection.expandTo(nextPosition, true), cause);
  }

  /// Expand the current selection to the start of the field.
  ///
  /// The selection will never shrink. The [TextSelection.extentOffset] will
  /// always be at the start of the field, regardless of the original order of
  /// [TextSelection.baseOffset] and [TextSelection.extentOffset].
  ///
  /// If [selectionEnabled] is false, keeps the selection collapsed and moves it
  /// to the start.
  ///
636 637
  /// If the selection is invalid, does nothing.
  ///
638 639 640 641 642 643 644
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [expandSelectionToEnd], which is the same but in the opposite
  ///     direction.
  void expandSelectionToStart(SelectionChangedCause cause) {
645 646 647
    if (!textEditingValue.selection.isValid) {
      return;
    }
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
    if (!selectionEnabled) {
      return moveSelectionToStart(cause);
    }

    const TextPosition nextPosition = TextPosition(
      offset: 0,
      affinity: TextAffinity.upstream,
    );
    setSelection(textEditingValue.selection.expandTo(nextPosition, true), cause);
  }

  /// Expand the current selection to the smallest selection that includes the
  /// start of the line.
  ///
  /// The selection will never shrink. The upper offset will be expanded to the
  /// beginning of its line, and the original order of baseOffset and
  /// [TextSelection.extentOffset] will be preserved.
  ///
  /// If [selectionEnabled] is false, keeps the selection collapsed and moves it
  /// left by line.
  ///
669 670
  /// If the selection is invalid, does nothing.
  ///
671 672 673 674 675 676 677
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [expandSelectionRightByLine], which is the same but in the opposite
  ///     direction.
  void expandSelectionLeftByLine(SelectionChangedCause cause) {
678 679 680
    if (!textEditingValue.selection.isValid) {
      return;
    }
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
    if (!selectionEnabled) {
      return moveSelectionLeftByLine(cause);
    }

    // If the lowest edge of the selection is at the start of a line, don't do
    // anything.
    // TODO(justinmc): Support selection with multiple TextAffinities.
    // https://github.com/flutter/flutter/issues/88135
    final TextSelection currentLine = textLayoutMetrics.getLineAtOffset(
      TextPosition(
        offset: textEditingValue.selection.start,
        affinity: textEditingValue.selection.isCollapsed
            ? textEditingValue.selection.affinity
            : TextAffinity.downstream,
      ),
    );
    if (currentLine.baseOffset == textEditingValue.selection.start) {
      return;
    }

    setSelection(textEditingValue.selection.expandTo(TextPosition(
      offset: currentLine.baseOffset,
      affinity: textEditingValue.selection.affinity,
    )), cause);
  }

  /// Expand the current selection to the smallest selection that includes the
  /// end of the line.
  ///
  /// The selection will never shrink. The lower offset will be expanded to the
  /// end of its line and the original order of [TextSelection.baseOffset] and
  /// [TextSelection.extentOffset] will be preserved.
  ///
  /// If [selectionEnabled] is false, keeps the selection collapsed and moves it
  /// right by line.
  ///
717 718
  /// If the selection is invalid, does nothing.
  ///
719 720 721 722 723 724 725
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [expandSelectionLeftByLine], which is the same but in the opposite
  ///     direction.
  void expandSelectionRightByLine(SelectionChangedCause cause) {
726 727 728
    if (!textEditingValue.selection.isValid) {
      return;
    }
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    if (!selectionEnabled) {
      return moveSelectionRightByLine(cause);
    }

    // If greatest edge is already at the end of a line, don't do anything.
    // TODO(justinmc): Support selection with multiple TextAffinities.
    // https://github.com/flutter/flutter/issues/88135
    final TextSelection currentLine = textLayoutMetrics.getLineAtOffset(
      TextPosition(
        offset: textEditingValue.selection.end,
        affinity: textEditingValue.selection.isCollapsed
            ? textEditingValue.selection.affinity
            : TextAffinity.upstream,
      ),
    );
    if (currentLine.extentOffset == textEditingValue.selection.end) {
      return;
    }

    final TextSelection nextSelection = textEditingValue.selection.expandTo(
      TextPosition(
        offset: currentLine.extentOffset,
        affinity: TextAffinity.upstream,
      ),
    );
    setSelection(nextSelection, cause);
  }

  /// Keeping selection's [TextSelection.baseOffset] fixed, move the
  /// [TextSelection.extentOffset] down by one line.
  ///
  /// If selectionEnabled is false, keeps the selection collapsed and just
  /// moves it down.
  ///
763 764
  /// If the selection is invalid, does nothing.
  ///
765 766 767 768 769 770
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [extendSelectionUp], which is same but in the opposite direction.
  void extendSelectionDown(SelectionChangedCause cause) {
771 772 773
    if (!textEditingValue.selection.isValid) {
      return;
    }
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
    if (!selectionEnabled) {
      return moveSelectionDown(cause);
    }

    // If the selection is collapsed at the end of the field already, then
    // nothing happens.
    if (textEditingValue.selection.isCollapsed &&
        textEditingValue.selection.extentOffset >= textEditingValue.text.length) {
      return;
    }

    int index =
        textLayoutMetrics.getTextPositionBelow(textEditingValue.selection.extent).offset;

    if (index == textEditingValue.selection.extentOffset) {
      index = textEditingValue.text.length;
      _wasSelectingVerticallyWithKeyboard = true;
    } else if (_wasSelectingVerticallyWithKeyboard) {
      index = _cursorResetLocation;
      _wasSelectingVerticallyWithKeyboard = false;
    } else {
      _cursorResetLocation = index;
    }

    final TextPosition nextPosition = TextPosition(
      offset: index,
      affinity: textEditingValue.selection.affinity,
    );
    setSelection(textEditingValue.selection.extendTo(nextPosition), cause);
  }

  /// If [selectionEnabled] is false, keeps the selection collapsed and moves it
  /// left.
  ///
808 809
  /// If the selection is invalid, does nothing.
  ///
810 811 812 813 814 815
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [extendSelectionRight], which is same but in the opposite direction.
  void extendSelectionLeft(SelectionChangedCause cause) {
816 817 818
    if (!textEditingValue.selection.isValid) {
      return;
    }
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
    if (!selectionEnabled) {
      return moveSelectionLeft(cause);
    }

    // If the selection is already all the way left, there is nothing to do.
    if (textEditingValue.selection.extentOffset <= 0) {
      return;
    }

    final int previousExtent = previousCharacter(
      textEditingValue.selection.extentOffset,
      textEditingValue.text,
    );

    final int distance = textEditingValue.selection.extentOffset - previousExtent;
    _cursorResetLocation -= distance;
    setSelection(textEditingValue.selection.extendTo(TextPosition(offset: previousExtent, affinity: textEditingValue.selection.affinity)), cause);
  }

  /// Extend the current selection to the start of
  /// [TextSelection.extentOffset]'s line.
  ///
  /// Uses [TextSelection.baseOffset] as a pivot point and doesn't change it.
  /// If [TextSelection.extentOffset] is right of [TextSelection.baseOffset],
  /// then the selection will be collapsed.
  ///
  /// If [selectionEnabled] is false, keeps the selection collapsed and moves it
  /// left by line.
  ///
848 849
  /// If the selection is invalid, does nothing.
  ///
850 851 852 853 854 855 856 857 858
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [extendSelectionRightByLine], which is same but in the opposite
  ///     direction.
  ///   * [expandSelectionRightByLine], which strictly grows the selection
  ///     regardless of the order.
  void extendSelectionLeftByLine(SelectionChangedCause cause) {
859 860 861
    if (!textEditingValue.selection.isValid) {
      return;
    }
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
    if (!selectionEnabled) {
      return moveSelectionLeftByLine(cause);
    }

    // When going left, we want to skip over any whitespace before the line,
    // so we go back to the first non-whitespace before asking for the line
    // bounds, since getLineAtOffset finds the line boundaries without
    // including whitespace (like the newline).
    final int startPoint = previousCharacter(
        textEditingValue.selection.extentOffset, textEditingValue.text, false);
    final TextSelection selectedLine = textLayoutMetrics.getLineAtOffset(
      TextPosition(offset: startPoint),
    );

    late final TextSelection nextSelection;
    // If the extent and base offsets would reverse order, then instead the
    // selection collapses.
    if (textEditingValue.selection.extentOffset > textEditingValue.selection.baseOffset) {
      nextSelection = textEditingValue.selection.copyWith(
        extentOffset: textEditingValue.selection.baseOffset,
      );
    } else {
      nextSelection = textEditingValue.selection.extendTo(TextPosition(
        offset: selectedLine.baseOffset,
      ));
    }

    setSelection(nextSelection, cause);
  }

  /// Keeping selection's [TextSelection.baseOffset] fixed, move the
  /// [TextSelection.extentOffset] right.
  ///
  /// If [selectionEnabled] is false, keeps the selection collapsed and moves it
  /// right.
  ///
898 899
  /// If the selection is invalid, does nothing.
  ///
900 901 902 903 904 905
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [extendSelectionLeft], which is same but in the opposite direction.
  void extendSelectionRight(SelectionChangedCause cause) {
906 907 908
    if (!textEditingValue.selection.isValid) {
      return;
    }
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    if (!selectionEnabled) {
      return moveSelectionRight(cause);
    }

    // If the selection is already all the way right, there is nothing to do.
    if (textEditingValue.selection.extentOffset >= textEditingValue.text.length) {
      return;
    }
    final int nextExtent = nextCharacter(
        textEditingValue.selection.extentOffset, textEditingValue.text);

    final int distance = nextExtent - textEditingValue.selection.extentOffset;
    _cursorResetLocation += distance;
    setSelection(textEditingValue.selection.extendTo(TextPosition(offset: nextExtent, affinity: textEditingValue.selection.affinity)), cause);
  }

  /// Extend the current selection to the end of [TextSelection.extentOffset]'s
  /// line.
  ///
  /// Uses [TextSelection.baseOffset] as a pivot point and doesn't change it. If
  /// [TextSelection.extentOffset] is left of [TextSelection.baseOffset], then
  /// collapses the selection.
  ///
  /// If [selectionEnabled] is false, keeps the selection collapsed and moves it
  /// right by line.
  ///
935 936
  /// If the selection is invalid, does nothing.
  ///
937 938 939 940 941 942 943 944 945
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [extendSelectionLeftByLine], which is same but in the opposite
  ///     direction.
  ///   * [expandSelectionRightByLine], which strictly grows the selection
  ///     regardless of the order.
  void extendSelectionRightByLine(SelectionChangedCause cause) {
946 947 948
    if (!textEditingValue.selection.isValid) {
      return;
    }
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    if (!selectionEnabled) {
      return moveSelectionRightByLine(cause);
    }

    final int startPoint = nextCharacter(
        textEditingValue.selection.extentOffset, textEditingValue.text, false);
    final TextSelection selectedLine = textLayoutMetrics.getLineAtOffset(
      TextPosition(offset: startPoint),
    );

    // If the extent and base offsets would reverse order, then instead the
    // selection collapses.
    late final TextSelection nextSelection;
    if (textEditingValue.selection.extentOffset < textEditingValue.selection.baseOffset) {
      nextSelection = textEditingValue.selection.copyWith(
        extentOffset: textEditingValue.selection.baseOffset,
      );
    } else {
      nextSelection = textEditingValue.selection.extendTo(TextPosition(
        offset: selectedLine.extentOffset,
        affinity: TextAffinity.upstream,
      ));
    }

    setSelection(nextSelection, cause);
  }

  /// Extend the current selection to the previous start of a word.
  ///
978 979
  /// If the selection is invalid, does nothing.
  ///
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.whiteSpace}
  ///
  /// {@template flutter.widgets.TextEditingActionTarget.stopAtReversal}
  /// The `stopAtReversal` parameter is false by default, meaning that it's
  /// ok for the base and extent to flip their order here. If set to true, then
  /// the selection will collapse when it would otherwise reverse its order. A
  /// selection that is already collapsed is not affected by this parameter.
  /// {@endtemplate}
  ///
  /// See also:
  ///
  ///   * [extendSelectionRightByWord], which is the same but in the opposite
  ///     direction.
  void extendSelectionLeftByWord(SelectionChangedCause cause,
      [bool includeWhitespace = true, bool stopAtReversal = false]) {
997 998 999
    if (!textEditingValue.selection.isValid) {
      return;
    }
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    // When the text is obscured, the whole thing is treated as one big word.
    if (obscureText) {
      return _extendSelectionToStart(cause);
    }

    debugAssertLayoutUpToDate();
    // If the selection is already all the way left, there is nothing to do.
    if (textEditingValue.selection.isCollapsed && textEditingValue.selection.extentOffset <= 0) {
      return;
    }

    final int leftOffset =
        _getLeftByWord(textEditingValue.selection.extentOffset, includeWhitespace);

    late final TextSelection nextSelection;
    if (stopAtReversal &&
        textEditingValue.selection.extentOffset > textEditingValue.selection.baseOffset &&
        leftOffset < textEditingValue.selection.baseOffset) {
      nextSelection = textEditingValue.selection.extendTo(TextPosition(offset: textEditingValue.selection.baseOffset));
    } else {
      nextSelection = textEditingValue.selection.extendTo(TextPosition(offset: leftOffset, affinity: textEditingValue.selection.affinity));
    }

    if (nextSelection == textEditingValue.selection) {
      return;
    }
    setSelection(nextSelection, cause);
  }

  /// Extend the current selection to the next end of a word.
  ///
1031 1032
  /// If the selection is invalid, does nothing.
  ///
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.whiteSpace}
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.stopAtReversal}
  ///
  /// See also:
  ///
  ///   * [extendSelectionLeftByWord], which is the same but in the opposite
  ///     direction.
  void extendSelectionRightByWord(SelectionChangedCause cause,
      [bool includeWhitespace = true, bool stopAtReversal = false]) {
1045 1046 1047
    if (!textEditingValue.selection.isValid) {
      return;
    }
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    debugAssertLayoutUpToDate();
    // When the text is obscured, the whole thing is treated as one big word.
    if (obscureText) {
      return _extendSelectionToEnd(cause);
    }

    // If the selection is already all the way right, there is nothing to do.
    if (textEditingValue.selection.isCollapsed &&
        textEditingValue.selection.extentOffset == textEditingValue.text.length) {
      return;
    }

    final int rightOffset =
        _getRightByWord(textEditingValue.selection.extentOffset, includeWhitespace);

    late final TextSelection nextSelection;
    if (stopAtReversal &&
        textEditingValue.selection.baseOffset > textEditingValue.selection.extentOffset &&
        rightOffset > textEditingValue.selection.baseOffset) {
      nextSelection = TextSelection.fromPosition(
        TextPosition(offset: textEditingValue.selection.baseOffset),
      );
    } else {
      nextSelection = textEditingValue.selection.extendTo(TextPosition(offset: rightOffset, affinity: textEditingValue.selection.affinity));
    }

    if (nextSelection == textEditingValue.selection) {
      return;
    }
    setSelection(nextSelection, cause);
  }

  /// Keeping selection's [TextSelection.baseOffset] fixed, move the
  /// [TextSelection.extentOffset] up by one
  /// line.
  ///
  /// If [selectionEnabled] is false, keeps the selection collapsed and moves it
  /// up.
  ///
1087 1088
  /// If the selection is invalid, does nothing.
  ///
1089 1090 1091 1092 1093 1094 1095
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [extendSelectionDown], which is the same but in the opposite
  ///     direction.
  void extendSelectionUp(SelectionChangedCause cause) {
1096 1097 1098
    if (!textEditingValue.selection.isValid) {
      return;
    }
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    if (!selectionEnabled) {
      return moveSelectionUp(cause);
    }

    // If the selection is collapsed at the beginning of the field already, then
    // nothing happens.
    if (textEditingValue.selection.isCollapsed && textEditingValue.selection.extentOffset <= 0.0) {
      return;
    }

    final TextPosition positionAbove =
        textLayoutMetrics.getTextPositionAbove(textEditingValue.selection.extent);
    late final TextSelection nextSelection;
    if (positionAbove.offset == textEditingValue.selection.extentOffset) {
      nextSelection = textEditingValue.selection.copyWith(
        extentOffset: 0,
        affinity: TextAffinity.upstream,
      );
      _wasSelectingVerticallyWithKeyboard = true;
    } else if (_wasSelectingVerticallyWithKeyboard) {
      nextSelection = textEditingValue.selection.copyWith(
        baseOffset: textEditingValue.selection.baseOffset,
        extentOffset: _cursorResetLocation,
      );
      _wasSelectingVerticallyWithKeyboard = false;
    } else {
      nextSelection = textEditingValue.selection.copyWith(
        baseOffset: textEditingValue.selection.baseOffset,
        extentOffset: positionAbove.offset,
        affinity: positionAbove.affinity,
      );
      _cursorResetLocation = nextSelection.extentOffset;
    }

    setSelection(nextSelection, cause);
  }

  /// Move the current selection to the leftmost point of the current line.
  ///
1138 1139
  /// If the selection is invalid, does nothing.
  ///
1140 1141 1142 1143 1144 1145 1146
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [moveSelectionRightByLine], which is the same but in the opposite
  ///     direction.
  void moveSelectionLeftByLine(SelectionChangedCause cause) {
1147 1148 1149
    if (!textEditingValue.selection.isValid) {
      return;
    }
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
    // If already at the left edge of the line, do nothing.
    final TextSelection currentLine = textLayoutMetrics.getLineAtOffset(
      textEditingValue.selection.extent,
    );
    if (currentLine.baseOffset == textEditingValue.selection.extentOffset) {
      return;
    }

    // When going left, we want to skip over any whitespace before the line,
    // so we go back to the first non-whitespace before asking for the line
    // bounds, since getLineAtOffset finds the line boundaries without
    // including whitespace (like the newline).
    final int startPoint = previousCharacter(
        textEditingValue.selection.extentOffset, textEditingValue.text, false);
    final TextSelection selectedLine = textLayoutMetrics.getLineAtOffset(
      TextPosition(offset: startPoint),
    );
    final TextSelection nextSelection = TextSelection.fromPosition(TextPosition(
      offset: selectedLine.baseOffset,
    ));

    setSelection(nextSelection, cause);
  }

  /// Move the current selection to the next line.
  ///
1176 1177
  /// If the selection is invalid, does nothing.
  ///
1178 1179 1180 1181 1182 1183
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [moveSelectionUp], which is the same but in the opposite direction.
  void moveSelectionDown(SelectionChangedCause cause) {
1184 1185 1186
    if (!textEditingValue.selection.isValid) {
      return;
    }
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
    // If the selection is collapsed at the end of the field already, then
    // nothing happens.
    if (textEditingValue.selection.isCollapsed &&
        textEditingValue.selection.extentOffset >= textEditingValue.text.length) {
      return;
    }

    final TextPosition positionBelow =
        textLayoutMetrics.getTextPositionBelow(textEditingValue.selection.extent);

    late final TextSelection nextSelection;
    if (positionBelow.offset == textEditingValue.selection.extentOffset) {
      nextSelection = textEditingValue.selection.copyWith(
        baseOffset: textEditingValue.text.length,
        extentOffset: textEditingValue.text.length,
      );
    } else {
      nextSelection = TextSelection.fromPosition(positionBelow);
    }

    if (textEditingValue.selection.extentOffset == textEditingValue.text.length) {
      _wasSelectingVerticallyWithKeyboard = false;
    } else {
      _cursorResetLocation = nextSelection.extentOffset;
    }

    setSelection(nextSelection, cause);
  }

  /// Move the current selection left by one character.
  ///
  /// If it can't be moved left, do nothing.
  ///
1220 1221
  /// If the selection is invalid, does nothing.
  ///
1222 1223 1224 1225 1226 1227
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [moveSelectionRight], which is the same but in the opposite direction.
  void moveSelectionLeft(SelectionChangedCause cause) {
1228 1229 1230
    if (!textEditingValue.selection.isValid) {
      return;
    }
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    // If the selection is already all the way left, there is nothing to do.
    if (textEditingValue.selection.isCollapsed && textEditingValue.selection.extentOffset <= 0) {
      return;
    }

    int previousExtent;
    if (textEditingValue.selection.start != textEditingValue.selection.end) {
      previousExtent = textEditingValue.selection.start;
    } else {
      previousExtent = previousCharacter(
          textEditingValue.selection.extentOffset, textEditingValue.text);
    }
    final TextSelection nextSelection = TextSelection.fromPosition(
      TextPosition(
        offset: previousExtent,
        affinity: textEditingValue.selection.affinity,
      ),
    );

    if (nextSelection == textEditingValue.selection) {
      return;
    }
    _cursorResetLocation -=
        textEditingValue.selection.extentOffset - nextSelection.extentOffset;
    setSelection(nextSelection, cause);
  }

  /// Move the current selection to the previous start of a word.
  ///
  /// A TextSelection that isn't collapsed will be collapsed and moved from the
  /// extentOffset.
  ///
1263 1264
  /// If the selection is invalid, does nothing.
  ///
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.whiteSpace}
  ///
  /// See also:
  ///
  ///   * [moveSelectionRightByWord], which is the same but in the opposite
  ///     direction.
  void moveSelectionLeftByWord(SelectionChangedCause cause,
      [bool includeWhitespace = true]) {
1275 1276 1277
    if (!textEditingValue.selection.isValid) {
      return;
    }
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
    // When the text is obscured, the whole thing is treated as one big word.
    if (obscureText) {
      return moveSelectionToStart(cause);
    }

    debugAssertLayoutUpToDate();
    // If the selection is already all the way left, there is nothing to do.
    if (textEditingValue.selection.isCollapsed && textEditingValue.selection.extentOffset <= 0) {
      return;
    }

    final int leftOffset =
        _getLeftByWord(textEditingValue.selection.extentOffset, includeWhitespace);
    final TextSelection nextSelection = TextSelection.fromPosition(TextPosition(offset: leftOffset, affinity: textEditingValue.selection.affinity));

    if (nextSelection == textEditingValue.selection) {
      return;
    }
    setSelection(nextSelection, cause);
  }

  /// Move the current selection to the right by one character.
  ///
1301
  /// If the selection is invalid or it can't be moved right, do nothing.
1302 1303 1304 1305 1306 1307 1308
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [moveSelectionLeft], which is the same but in the opposite direction.
  void moveSelectionRight(SelectionChangedCause cause) {
1309 1310 1311
    if (!textEditingValue.selection.isValid) {
      return;
    }
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
    // If the selection is already all the way right, there is nothing to do.
    if (textEditingValue.selection.isCollapsed &&
        textEditingValue.selection.extentOffset >= textEditingValue.text.length) {
      return;
    }

    int nextExtent;
    if (textEditingValue.selection.start != textEditingValue.selection.end) {
      nextExtent = textEditingValue.selection.end;
    } else {
      nextExtent = nextCharacter(
          textEditingValue.selection.extentOffset, textEditingValue.text);
    }
    final TextSelection nextSelection = TextSelection.fromPosition(TextPosition(
      offset: nextExtent,
    ));

    if (nextSelection == textEditingValue.selection) {
      return;
    }
    setSelection(nextSelection, cause);
  }

  /// Move the current selection to the rightmost point of the current line.
  ///
1337 1338
  /// If the selection is invalid, does nothing.
  ///
1339 1340 1341 1342 1343 1344 1345
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [moveSelectionLeftByLine], which is the same but in the opposite
  ///     direction.
  void moveSelectionRightByLine(SelectionChangedCause cause) {
1346 1347 1348
    if (!textEditingValue.selection.isValid) {
      return;
    }
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    // If already at the right edge of the line, do nothing.
    final TextSelection currentLine = textLayoutMetrics.getLineAtOffset(
      textEditingValue.selection.extent,
    );
    if (currentLine.extentOffset == textEditingValue.selection.extentOffset) {
      return;
    }

    // When going right, we want to skip over any whitespace after the line,
    // so we go forward to the first non-whitespace character before asking
    // for the line bounds, since getLineAtOffset finds the line
    // boundaries without including whitespace (like the newline).
    final int startPoint = nextCharacter(
        textEditingValue.selection.extentOffset, textEditingValue.text, false);
    final TextSelection selectedLine = textLayoutMetrics.getLineAtOffset(
      TextPosition(
        offset: startPoint,
        affinity: TextAffinity.upstream,
      ),
    );
    final TextSelection nextSelection = TextSelection.fromPosition(TextPosition(
      offset: selectedLine.extentOffset,
      affinity: TextAffinity.upstream,
    ));
    setSelection(nextSelection, cause);
  }

  /// Move the current selection to the next end of a word.
  ///
  /// A TextSelection that isn't collapsed will be collapsed and moved from the
  /// extentOffset.
  ///
1381 1382
  /// If the selection is invalid, does nothing.
  ///
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.whiteSpace}
  ///
  /// See also:
  ///
  ///   * [moveSelectionLeftByWord], which is the same but in the opposite
  ///     direction.
  void moveSelectionRightByWord(SelectionChangedCause cause,
      [bool includeWhitespace = true]) {
1393 1394 1395
    if (!textEditingValue.selection.isValid) {
      return;
    }
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
    // When the text is obscured, the whole thing is treated as one big word.
    if (obscureText) {
      return moveSelectionToEnd(cause);
    }

    debugAssertLayoutUpToDate();
    // If the selection is already all the way right, there is nothing to do.
    if (textEditingValue.selection.isCollapsed &&
        textEditingValue.selection.extentOffset == textEditingValue.text.length) {
      return;
    }

    final int rightOffset =
        _getRightByWord(textEditingValue.selection.extentOffset, includeWhitespace);
    final TextSelection nextSelection = TextSelection.fromPosition(TextPosition(offset: rightOffset, affinity: textEditingValue.selection.affinity));

    if (nextSelection == textEditingValue.selection) {
      return;
    }
    setSelection(nextSelection, cause);
  }

  /// Move the current selection to the end of the field.
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [moveSelectionToStart], which is the same but in the opposite
  ///     direction.
  void moveSelectionToEnd(SelectionChangedCause cause) {
    final TextPosition nextPosition = TextPosition(
      offset: textEditingValue.text.length,
    );
    setSelection(TextSelection.fromPosition(nextPosition), cause);
  }

  /// Move the current selection to the start of the field.
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [moveSelectionToEnd], which is the same but in the opposite direction.
  void moveSelectionToStart(SelectionChangedCause cause) {
    const TextPosition nextPosition = TextPosition(
      offset: 0,
      affinity: TextAffinity.upstream,
    );
    setSelection(TextSelection.fromPosition(nextPosition), cause);
  }

  /// Move the current selection up by one line.
  ///
1450 1451
  /// If the selection is invalid, does nothing.
  ///
1452 1453 1454 1455 1456 1457
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  ///
  /// See also:
  ///
  ///   * [moveSelectionDown], which is the same but in the opposite direction.
  void moveSelectionUp(SelectionChangedCause cause) {
1458 1459 1460
    if (!textEditingValue.selection.isValid) {
      return;
    }
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
    final int nextIndex =
        textLayoutMetrics.getTextPositionAbove(textEditingValue.selection.extent).offset;

    if (nextIndex == textEditingValue.selection.extentOffset) {
      _wasSelectingVerticallyWithKeyboard = false;
      return moveSelectionToStart(cause);
    }
    _cursorResetLocation = nextIndex;

    setSelection(TextSelection.fromPosition(TextPosition(offset: nextIndex, affinity: textEditingValue.selection.affinity)), cause);
  }

  /// Select the entire text value.
  ///
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  void selectAll(SelectionChangedCause cause) {
    setSelection(
      textEditingValue.selection.copyWith(
        baseOffset: 0,
        extentOffset: textEditingValue.text.length,
      ),
      cause,
    );
  }

  /// {@template flutter.widgets.TextEditingActionTarget.copySelection}
  /// Copy current selection to [Clipboard].
  /// {@endtemplate}
  ///
1490 1491
  /// If the selection is collapsed or invalid, does nothing.
  ///
1492 1493 1494 1495 1496
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  void copySelection(SelectionChangedCause cause) {
    final TextSelection selection = textEditingValue.selection;
    final String text = textEditingValue.text;
    assert(selection != null);
1497
    if (selection.isCollapsed || !selection.isValid) {
1498 1499 1500 1501 1502 1503 1504 1505 1506
      return;
    }
    Clipboard.setData(ClipboardData(text: selection.textInside(text)));
  }

  /// {@template flutter.widgets.TextEditingActionTarget.cutSelection}
  /// Cut current selection to Clipboard.
  /// {@endtemplate}
  ///
1507 1508
  /// If [readOnly] is true or the selection is invalid, does nothing.
  ///
1509 1510
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  void cutSelection(SelectionChangedCause cause) {
1511 1512
    final TextSelection selection = textEditingValue.selection;
    if (readOnly || !selection.isValid) {
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
      return;
    }
    final String text = textEditingValue.text;
    assert(selection != null);
    if (selection.isCollapsed) {
      return;
    }
    Clipboard.setData(ClipboardData(text: selection.textInside(text)));
    setTextEditingValue(
      TextEditingValue(
        text: selection.textBefore(text) + selection.textAfter(text),
        selection: TextSelection.collapsed(
          offset: math.min(selection.start, selection.end),
          affinity: selection.affinity,
        ),
      ),
      cause,
    );
  }

  /// {@template flutter.widgets.TextEditingActionTarget.pasteText}
  /// Paste text from [Clipboard].
  /// {@endtemplate}
  ///
  /// If there is currently a selection, it will be replaced.
  ///
1539 1540
  /// If [readOnly] is true or the selection is invalid, does nothing.
  ///
1541 1542
  /// {@macro flutter.widgets.TextEditingActionTarget.cause}
  Future<void> pasteText(SelectionChangedCause cause) async {
1543 1544
    final TextSelection selection = textEditingValue.selection;
    if (readOnly || !selection.isValid) {
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
      return;
    }
    final String text = textEditingValue.text;
    assert(selection != null);
    if (!selection.isValid) {
      return;
    }
    // Snapshot the input before using `await`.
    // See https://github.com/flutter/flutter/issues/11427
    final ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
    if (data == null) {
      return;
    }
    setTextEditingValue(
      TextEditingValue(
        text: selection.textBefore(text) +
            data.text! +
            selection.textAfter(text),
        selection: TextSelection.collapsed(
          offset:
              math.min(selection.start, selection.end) + data.text!.length,
          affinity: selection.affinity,
        ),
      ),
      cause,
    );
  }
}