code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def generate_note_body( music: "Music", compact_repeats: bool = True, **kwargs ) -> "list[str]": """Generate ABC note body from Music object. Parameters ---------- music : :class:`muspy.Music` Music object to generate ABC note body. """ time_sigs = [ _ABCTimeSignature(time_s...
Generate ABC note body from Music object. Parameters ---------- music : :class:`muspy.Music` Music object to generate ABC note body.
generate_note_body
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def write_abc(path: Union[str, Path], music: "Music", **kwargs): """Write a Music object to an ABC file. Parameters ---------- path : str or Path Path to write the ABC file. music : :class:`muspy.Music` Music object to write. """ file_lines = generate_header(music) file...
Write a Music object to an ABC file. Parameters ---------- path : str or Path Path to write the ABC file. music : :class:`muspy.Music` Music object to write.
write_abc
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def synthesize( music: "Music", soundfont_path: Union[str, Path] = None, rate: int = 44100, gain: float = 1, options: str = None, ) -> ndarray: """Synthesize a Music object to raw audio. Parameters ---------- music : :class:`muspy.Music` Music object to write. soundfont_...
Synthesize a Music object to raw audio. Parameters ---------- music : :class:`muspy.Music` Music object to write. soundfont_path : str or Path, optional Path to the soundfount file. Defaults to the path to the downloaded MuseScore General soundfont. rate : int, default: 4410...
synthesize
python
salu133445/muspy
muspy/outputs/audio.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/audio.py
MIT
def write_audio( path: Union[str, Path], music: "Music", audio_format: str = "auto", soundfont_path: Union[str, Path] = None, rate: int = 44100, gain: float = 1, options: str = None, ): """Write a Music object to an audio file. Supported formats include WAV, AIFF, FLAC and OGA. ...
Write a Music object to an audio file. Supported formats include WAV, AIFF, FLAC and OGA. Parameters ---------- path : str or Path Path to write the audio file. music : :class:`muspy.Music` Music object to write. audio_format : str, default: 'auto' File format to write....
write_audio
python
salu133445/muspy
muspy/outputs/audio.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/audio.py
MIT
def to_event_representation( music: "Music", use_single_note_off_event: bool = False, use_end_of_sequence_event: bool = False, encode_velocity: bool = False, force_velocity_event: bool = True, max_time_shift: int = 100, velocity_bins: int = 32, dtype=int, ) -> ndarray: """Encode a Mu...
Encode a Music object into event-based representation. The event-based represetantion represents music as a sequence of events, including note-on, note-off, time-shift and velocity events. The output shape is M x 1, where M is the number of events. The values encode the events. The default configuratio...
to_event_representation
python
salu133445/muspy
muspy/outputs/event.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/event.py
MIT
def to_time_shift_events(cls, time_shift) -> List[str]: """Return a list of time-shift events for a given time-shift.""" if time_shift <= 100: return [f"time_shift_{time_shift}"] events = [] div, mod = divmod(time_shift, 100) for _ in range(div): events.ap...
Return a list of time-shift events for a given time-shift.
to_time_shift_events
python
salu133445/muspy
muspy/outputs/event.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/event.py
MIT
def to_default_event_sequence( music: "Music", resolution: int = None ) -> DefaultEventSequence: """Return a Music object as a DefaultEventSequence object.""" # Adjust resolution if resolution is not None: music.adjust_resolution(resolution) # Collect notes notes = [] for track in m...
Return a Music object as a DefaultEventSequence object.
to_default_event_sequence
python
salu133445/muspy
muspy/outputs/event.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/event.py
MIT
def to_default_event_representation(music: "Music", dtype=int) -> ndarray: """Encode a Music object into the default event representation.""" seq = to_default_event_sequence(music) return np.array(seq, dtype=dtype)
Encode a Music object into the default event representation.
to_default_event_representation
python
salu133445/muspy
muspy/outputs/event.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/event.py
MIT
def to_performance_event_sequence( music: "Music", resolution: int = None ) -> PerformanceEventSequence: """Return a Music object as a PerformanceEventSequence object.""" # Adjust resolution if resolution is not None: music.adjust_resolution(resolution) # Collect notes notes = [] fo...
Return a Music object as a PerformanceEventSequence object.
to_performance_event_sequence
python
salu133445/muspy
muspy/outputs/event.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/event.py
MIT
def to_performance_event_representation(music: "Music", dtype=int) -> ndarray: """Encode a Music object to the performance event representation.""" seq = to_performance_event_sequence(music) return np.array(seq, dtype=dtype)
Encode a Music object to the performance event representation.
to_performance_event_representation
python
salu133445/muspy
muspy/outputs/event.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/event.py
MIT
def to_remi_event_sequence(music: "Music") -> REMIEventSequence: """Return a Music object as a REMIEventSequence object.""" # Adjust resolution music.adjust_resolution(16) # Collect notes notes = [] for track in music.tracks: notes.extend(track.notes) # Raise an error if no notes i...
Return a Music object as a REMIEventSequence object.
to_remi_event_sequence
python
salu133445/muspy
muspy/outputs/event.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/event.py
MIT
def to_remi_event_representation(music: "Music", dtype=int) -> ndarray: """Encode a Music object into the remi event representation.""" seq = to_remi_event_sequence(music) return np.array(seq, dtype=dtype)
Encode a Music object into the remi event representation.
to_remi_event_representation
python
salu133445/muspy
muspy/outputs/event.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/event.py
MIT
def save_json( path: Union[str, Path, TextIO], music: "Music", skip_missing: bool = True, ensure_ascii: bool = False, compressed: bool = None, **kwargs ): """Save a Music object to a JSON file. Parameters ---------- path : str, Path or TextIO Path or file to save the JSO...
Save a Music object to a JSON file. Parameters ---------- path : str, Path or TextIO Path or file to save the JSON data. music : :class:`muspy.Music` Music object to save. skip_missing : bool, default: True Whether to skip attributes with value None or those that are ...
save_json
python
salu133445/muspy
muspy/outputs/json.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/json.py
MIT
def to_delta_time(midi_track: MidiTrack): """Convert a mido MidiTrack object from absolute time to delta time. Parameters ---------- midi_track : :class:`mido.MidiTrack` object mido MidiTrack object to convert. """ # Sort messages by absolute time midi_track.sort(key=lambda x: x.ti...
Convert a mido MidiTrack object from absolute time to delta time. Parameters ---------- midi_track : :class:`mido.MidiTrack` object mido MidiTrack object to convert.
to_delta_time
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_mido_tempo(tempo: Tempo) -> MetaMessage: """Return a Tempo object as a mido MetaMessage object. Timing is in absolute time, NOT in delta time. """ return MetaMessage( "set_tempo", time=tempo.time, tempo=bpm2tempo(tempo.qpm) )
Return a Tempo object as a mido MetaMessage object. Timing is in absolute time, NOT in delta time.
to_mido_tempo
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_mido_key_signature( key_signature: KeySignature, ) -> Optional[MetaMessage]: """Return a KeySignature object as a mido MetaMessage object. Timing is in absolute time, NOT in delta time. """ # TODO: `key_signature.root_str` might be given if key_signature.root is None: return Non...
Return a KeySignature object as a mido MetaMessage object. Timing is in absolute time, NOT in delta time.
to_mido_key_signature
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_mido_time_signature(time_signature: TimeSignature) -> MetaMessage: """Return a TimeSignature object as a mido MetaMessage object. Timing is in absolute time, NOT in delta time. """ return MetaMessage( "time_signature", time=time_signature.time, numerator=time_signature.n...
Return a TimeSignature object as a mido MetaMessage object. Timing is in absolute time, NOT in delta time.
to_mido_time_signature
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_mido_meta_track(music: "Music") -> MidiTrack: """Return a mido MidiTrack containing metadata of a Music object. Parameters ---------- music : :class:`muspy.Music` object Music object to convert. Returns ------- :class:`mido.MidiTrack` object Converted mido MidiTrack ...
Return a mido MidiTrack containing metadata of a Music object. Parameters ---------- music : :class:`muspy.Music` object Music object to convert. Returns ------- :class:`mido.MidiTrack` object Converted mido MidiTrack object.
to_mido_meta_track
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_mido_note_on_note_off( note: Note, channel: int, use_note_off_message: bool = False ) -> Tuple[Message, Message]: """Return a Note object as mido Message objects. Timing is in absolute time, NOT in delta time. Parameters ---------- note : :class:`muspy.Note` object Note object t...
Return a Note object as mido Message objects. Timing is in absolute time, NOT in delta time. Parameters ---------- note : :class:`muspy.Note` object Note object to convert. channel : int Channel of the MIDI message. use_note_off_message : bool, default: False Whether to...
to_mido_note_on_note_off
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_mido_track( track: Track, channel: int = None, use_note_off_message: bool = False, ) -> MidiTrack: """Return a Track object as a mido MidiTrack object. Parameters ---------- track : :class:`muspy.Track` object Track object to convert. channel : int, optional Channel numbe...
Return a Track object as a mido MidiTrack object. Parameters ---------- track : :class:`muspy.Track` object Track object to convert. channel : int, optional Channel number. Defaults to 10 for drums and 0 for other instruments. use_note_off_message : bool, default: False ...
to_mido_track
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_mido(music: "Music", use_note_off_message: bool = False): """Return a Music object as a MidiFile object. Parameters ---------- music : :class:`muspy.Music` object Music object to convert. use_note_off_message : bool, default: False Whether to use note-off messages. If False, ...
Return a Music object as a MidiFile object. Parameters ---------- music : :class:`muspy.Music` object Music object to convert. use_note_off_message : bool, default: False Whether to use note-off messages. If False, note-on messages with zero velocity are used instead. The advant...
to_mido
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def write_midi_mido( path: Union[str, Path], music: "Music", use_note_off_message: bool = False ): """Write a Music object to a MIDI file using mido as backend. Parameters ---------- path : str or Path Path to write the MIDI file. music : :class:`muspy.Music` object Music object...
Write a Music object to a MIDI file using mido as backend. Parameters ---------- path : str or Path Path to write the MIDI file. music : :class:`muspy.Music` object Music object to write. use_note_off_message : bool, default: False Whether to use note-off messages. If False,...
write_midi_mido
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_pretty_midi_lyric(lyric: Lyric, map_time: Callable = None) -> PmLyric: """Return a Lyric object as a pretty_midi Lyric object.""" if map_time is not None: time = map_time(lyric.time) else: time = lyric.time return PmLyric(text=lyric.lyric, time=time)
Return a Lyric object as a pretty_midi Lyric object.
to_pretty_midi_lyric
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_pretty_midi_note(note: Note, map_time: Callable = None) -> PmNote: """Return a Note object as a pretty_midi Note object.""" if map_time is not None: start = map_time(note.start) end = map_time(note.end) else: start = note.start end = note.end velocity = note.veloci...
Return a Note object as a pretty_midi Note object.
to_pretty_midi_note
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_pretty_midi_instrument( track: Track, map_time: Callable = None ) -> PmInstrument: """Return a Track object as a pretty_midi Instrument object.""" instrument = PmInstrument( program=track.program, is_drum=track.is_drum, name=track.name ) for note in track.notes: instrument.not...
Return a Track object as a pretty_midi Instrument object.
to_pretty_midi_instrument
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_pretty_midi(music: "Music") -> PrettyMIDI: """Return a Music object as a PrettyMIDI object. Tempo changes are not supported yet. Parameters ---------- music : :class:`muspy.Music` object Music object to convert. Returns ------- :class:`pretty_midi.PrettyMIDI` Co...
Return a Music object as a PrettyMIDI object. Tempo changes are not supported yet. Parameters ---------- music : :class:`muspy.Music` object Music object to convert. Returns ------- :class:`pretty_midi.PrettyMIDI` Converted PrettyMIDI object. Notes ----- Tempo...
to_pretty_midi
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def write_midi( path: Union[str, Path], music: "Music", backend: str = "mido", **kwargs: Any, ): """Write a Music object to a MIDI file. Parameters ---------- path : str or Path Path to write the MIDI file. music : :class:`muspy.Music` Music object to write. back...
Write a Music object to a MIDI file. Parameters ---------- path : str or Path Path to write the MIDI file. music : :class:`muspy.Music` Music object to write. backend: {'mido', 'pretty_midi'}, default: 'mido' Backend to use. See Also -------- write_midi_mido : ...
write_midi
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_miditoolkit_key_signature( key_signature: KeySignature, ) -> Optional[MtkKeySignature]: """Return a KeySignature object as a miditoolkit KeySignature.""" # TODO: `key_signature.root_str` might be given if key_signature.root is None: return None if key_signature.mode not in ("major", "...
Return a KeySignature object as a miditoolkit KeySignature.
to_miditoolkit_key_signature
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_miditoolkit_time_signature( time_signature: TimeSignature, ) -> MtkTimeSignature: """Return a TimeSignature object as a miditoolkit TimeSignature.""" return MtkTimeSignature( numerator=time_signature.numerator, denominator=time_signature.denominator, time=time_signature.time, ...
Return a TimeSignature object as a miditoolkit TimeSignature.
to_miditoolkit_time_signature
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_miditoolkit_note(note: Note) -> MtkNote: """Return a Note object as a miditoolkit Note object.""" velocity = note.velocity if note.velocity is not None else DEFAULT_VELOCITY return MtkNote( velocity=velocity, pitch=note.pitch, start=note.time, end=note.end )
Return a Note object as a miditoolkit Note object.
to_miditoolkit_note
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_miditoolkit_instrument(track: Track) -> MtkInstrument: """Return a Track object as a miditoolkit Instrument object.""" instrument = MtkInstrument( program=track.program, is_drum=track.is_drum, name=track.name ) for note in track.notes: instrument.notes.append(to_miditoolkit_note(n...
Return a Track object as a miditoolkit Instrument object.
to_miditoolkit_instrument
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_miditoolkit(music: "Music") -> MtkMidiFile: """Return a Music object as a miditoolkit object. Tempo changes are not supported yet. Parameters ---------- music : :class:`muspy.Music` object Music object to convert. Returns ------- :class:`pretty_midi.PrettyMIDI` ...
Return a Music object as a miditoolkit object. Tempo changes are not supported yet. Parameters ---------- music : :class:`muspy.Music` object Music object to convert. Returns ------- :class:`pretty_midi.PrettyMIDI` Converted PrettyMIDI object. Notes ----- Temp...
to_miditoolkit
python
salu133445/muspy
muspy/outputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/midi.py
MIT
def to_music21_metronome(tempo: Tempo) -> MetronomeMark: """Return a Tempo object as a music21 MetronomeMark object.""" metronome = MetronomeMark(number=tempo.qpm) metronome.offset = tempo.time return metronome
Return a Tempo object as a music21 MetronomeMark object.
to_music21_metronome
python
salu133445/muspy
muspy/outputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/music21.py
MIT
def to_music21_key(key_signature: KeySignature) -> Key: """Return a KeySignature object as a music21 Key object.""" if key_signature.root_str is not None: tonic = key_signature.root_str elif key_signature.root is not None: tonic = PITCH_NAMES[key_signature.root] elif key_signature.fifths...
Return a KeySignature object as a music21 Key object.
to_music21_key
python
salu133445/muspy
muspy/outputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/music21.py
MIT
def to_music21_metadata(metadata: Metadata) -> M21MetaData: """Return a Metadata object as a music21 Metadata object. Parameters ---------- metadata : :class:`muspy.Metadata` Metadata object to convert. Returns ------- `music21.metadata.Metadata` Converted music21 Metadata ...
Return a Metadata object as a music21 Metadata object. Parameters ---------- metadata : :class:`muspy.Metadata` Metadata object to convert. Returns ------- `music21.metadata.Metadata` Converted music21 Metadata object.
to_music21_metadata
python
salu133445/muspy
muspy/outputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/music21.py
MIT
def to_music21(music: "Music") -> Score: """Return a Music object as a music21 Score object. Parameters ---------- music : :class:`muspy.Music` Music object to convert. Returns ------- `music21.stream.Score` Converted music21 Score object. """ # Create a new score ...
Return a Music object as a music21 Score object. Parameters ---------- music : :class:`muspy.Music` Music object to convert. Returns ------- `music21.stream.Score` Converted music21 Score object.
to_music21
python
salu133445/muspy
muspy/outputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/music21.py
MIT
def write_musicxml( path: Union[str, Path], music: "Music", compressed: bool = None ): """Write a Music object to a MusicXML file. Parameters ---------- path : str or Path Path to write the MusicXML file. music : :class:`muspy.Music` Music object to write. compressed : bool,...
Write a Music object to a MusicXML file. Parameters ---------- path : str or Path Path to write the MusicXML file. music : :class:`muspy.Music` Music object to write. compressed : bool, optional Whether to write to a compressed MusicXML file. If None, infer from the ...
write_musicxml
python
salu133445/muspy
muspy/outputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/musicxml.py
MIT
def to_note_representation( music: "Music", use_start_end: bool = False, encode_velocity: bool = True, dtype: Union[np.dtype, type, str] = int, ) -> ndarray: """Encode a Music object into note-based representation. The note-based represetantion represents music as a sequence of (time, pitch...
Encode a Music object into note-based representation. The note-based represetantion represents music as a sequence of (time, pitch, duration, velocity) tuples. For example, a note Note(time=0, duration=4, pitch=60, velocity=64) will be encoded as a tuple (0, 60, 4, 64). The output shape is N * D, where...
to_note_representation
python
salu133445/muspy
muspy/outputs/note.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/note.py
MIT
def to_pypianoroll(music: "Music") -> Multitrack: """Return a Music object as a Multitrack object. Parameters ---------- music : :class:`muspy.Music` Music object to convert. Returns ------- multitrack : :class:`pypianoroll.Multitrack` Converted Multitrack object. """ ...
Return a Music object as a Multitrack object. Parameters ---------- music : :class:`muspy.Music` Music object to convert. Returns ------- multitrack : :class:`pypianoroll.Multitrack` Converted Multitrack object.
to_pypianoroll
python
salu133445/muspy
muspy/outputs/pianoroll.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/pianoroll.py
MIT
def to_pianoroll_representation( music: "Music", encode_velocity: bool = True, dtype: Union[np.dtype, type, str] = None, ) -> ndarray: """Encode notes into piano-roll representation. Parameters ---------- music : :class:`muspy.Music` Music object to encode. encode_velocity : boo...
Encode notes into piano-roll representation. Parameters ---------- music : :class:`muspy.Music` Music object to encode. encode_velocity : bool, default: True Whether to encode velocities. If True, a binary-valued array will be return. Otherwise, an integer array will be return. ...
to_pianoroll_representation
python
salu133445/muspy
muspy/outputs/pianoroll.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/pianoroll.py
MIT
def to_pitch_representation( music: "Music", use_hold_state: bool = False, dtype: Union[np.dtype, type, str] = int, ) -> ndarray: """Encode a Music object into pitch-based representation. The pitch-based represetantion represents music as a sequence of pitch, rest and (optional) hold tokens. On...
Encode a Music object into pitch-based representation. The pitch-based represetantion represents music as a sequence of pitch, rest and (optional) hold tokens. Only monophonic melodies are compatible with this representation. The output shape is T x 1, where T is the number of time steps. The values in...
to_pitch_representation
python
salu133445/muspy
muspy/outputs/pitch.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/pitch.py
MIT
def save( path: Union[str, Path, TextIO], music: "Music", kind: str = None, **kwargs, ): """Save a Music object loselessly to a JSON or a YAML file. This is a wrapper function for :func:`muspy.save_json` and :func:`muspy.save_yaml`. Parameters ---------- path : str, Path or TextIO ...
Save a Music object loselessly to a JSON or a YAML file. This is a wrapper function for :func:`muspy.save_json` and :func:`muspy.save_yaml`. Parameters ---------- path : str, Path or TextIO Path or file to save the data. music : :class:`muspy.Music` Music object to save. ki...
save
python
salu133445/muspy
muspy/outputs/wrappers.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/wrappers.py
MIT
def write( path: Union[str, Path], music: "Music", kind: str = None, **kwargs, ): """Write a Music object to a MIDI/MusicXML/ABC/audio file. Parameters ---------- path : str or Path Path to write the file. music : :class:`muspy.Music` Music object to convert. kind : {'midi',...
Write a Music object to a MIDI/MusicXML/ABC/audio file. Parameters ---------- path : str or Path Path to write the file. music : :class:`muspy.Music` Music object to convert. kind : {'midi', 'musicxml', 'abc', 'audio'}, optional Format to save. Defaults to infer from the ext...
write
python
salu133445/muspy
muspy/outputs/wrappers.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/wrappers.py
MIT
def to_object( music: "Music", kind: str, **kwargs ) -> Union[Stream, MidiFile, PrettyMIDI, Multitrack]: """Return a Music object as an object in other libraries. Supported classes are `music21.Stream`, :class:`mido.MidiTrack`, :class:`pretty_midi.PrettyMIDI` and :class:`pypianoroll.Multitrack`. P...
Return a Music object as an object in other libraries. Supported classes are `music21.Stream`, :class:`mido.MidiTrack`, :class:`pretty_midi.PrettyMIDI` and :class:`pypianoroll.Multitrack`. Parameters ---------- music : :class:`muspy.Music` Music object to convert. kind : str, {'music21...
to_object
python
salu133445/muspy
muspy/outputs/wrappers.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/wrappers.py
MIT
def to_representation(music: "Music", kind: str, **kwargs) -> ndarray: """Return a Music object in a specific representation. Parameters ---------- music : :class:`muspy.Music` Music object to convert. kind : str, {'pitch', 'piano-roll', 'event', 'note'} Target representation. ...
Return a Music object in a specific representation. Parameters ---------- music : :class:`muspy.Music` Music object to convert. kind : str, {'pitch', 'piano-roll', 'event', 'note'} Target representation. Returns ------- array : ndarray Converted representation. ...
to_representation
python
salu133445/muspy
muspy/outputs/wrappers.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/wrappers.py
MIT
def save_yaml( path: Union[str, Path, TextIO], music: "Music", skip_missing: bool = True, allow_unicode: bool = True, compressed: bool = None, **kwargs ): """Save a Music object to a YAML file. Parameters ---------- path : str, Path or TextIO Path or file to save the YAM...
Save a Music object to a YAML file. Parameters ---------- path : str, Path or TextIO Path or file to save the YAML data. music : :class:`muspy.Music` Music object to save. skip_missing : bool, default: True Whether to skip attributes with value None or those that are ...
save_yaml
python
salu133445/muspy
muspy/outputs/yaml.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/yaml.py
MIT
def validate_json(path: Union[str, Path]): """Validate a file against the JSON schema. Parameters ---------- path : str or Path Path to the file to validate. """ if not _HAS_JSONSCHEMA: raise RuntimeError( "The jsonschema library is required for JSON schema validati...
Validate a file against the JSON schema. Parameters ---------- path : str or Path Path to the file to validate.
validate_json
python
salu133445/muspy
muspy/schemas/utils.py
https://github.com/salu133445/muspy/blob/master/muspy/schemas/utils.py
MIT
def validate_yaml(path: Union[str, Path]): """Validate a file against the YAML schema. Parameters ---------- path : str or Path Path to the file to validate. """ if not _HAS_YAMALE: raise RuntimeError( "The Yamale library is required for YAML schema validation. " ...
Validate a file against the YAML schema. Parameters ---------- path : str or Path Path to the file to validate.
validate_yaml
python
salu133445/muspy
muspy/schemas/utils.py
https://github.com/salu133445/muspy/blob/master/muspy/schemas/utils.py
MIT
def validate_musicxml(path: Union[str, Path]): """Validate a file against the MusicXML schema. Parameters ---------- path : str or Path Path to the file to validate. """ if not _HAS_XMLSCHEMA: raise RuntimeError( "The xmlschema library is required for MusicXML schem...
Validate a file against the MusicXML schema. Parameters ---------- path : str or Path Path to the file to validate.
validate_musicxml
python
salu133445/muspy
muspy/schemas/utils.py
https://github.com/salu133445/muspy/blob/master/muspy/schemas/utils.py
MIT
def _to_note_counts(note_value) -> List[int]: """Return a list of counts of notes that sum to a note value. For example, a note value of 1.75 will be decoposed into a whole note, a half note and a quarter note, respectively. The return list is of length 12, where the first value corresponds to the coun...
Return a list of counts of notes that sum to a note value. For example, a note value of 1.75 will be decoposed into a whole note, a half note and a quarter note, respectively. The return list is of length 12, where the first value corresponds to the count of double whole notes and the last value corres...
_to_note_counts
python
salu133445/muspy
muspy/visualization/score.py
https://github.com/salu133445/muspy/blob/master/muspy/visualization/score.py
MIT
def to_note_codes(note_value) -> List[str]: """Return a note value as a list of note codes. For example, a note value of 1.75 will be decoposed into a whole note, a half note and a quarter note, respectively. """ note_code = COMMON_NOTE_CODES.get(note_value) if note_code is not None: r...
Return a note value as a list of note codes. For example, a note value of 1.75 will be decoposed into a whole note, a half note and a quarter note, respectively.
to_note_codes
python
salu133445/muspy
muspy/visualization/score.py
https://github.com/salu133445/muspy/blob/master/muspy/visualization/score.py
MIT
def to_note_codes_alt(note_value) -> List[str]: """Return a note value as a list of note codes with straight beams. This is useful for making chords as all the notes comes with a straight beam. For example, a note value of 1.75 will be decomposed into a whole note, a half note and a quarter note, respe...
Return a note value as a list of note codes with straight beams. This is useful for making chords as all the notes comes with a straight beam. For example, a note value of 1.75 will be decomposed into a whole note, a half note and a quarter note, respectively.
to_note_codes_alt
python
salu133445/muspy
muspy/visualization/score.py
https://github.com/salu133445/muspy/blob/master/muspy/visualization/score.py
MIT
def get_time_signature_code(number: int) -> str: """Return a string for a time signature number.""" if number > 10: div, mod = divmod(number, 10) return chr(57472 + div) + chr(57472 + mod) return chr(57472 + number)
Return a string for a time signature number.
get_time_signature_code
python
salu133445/muspy
muspy/visualization/score.py
https://github.com/salu133445/muspy/blob/master/muspy/visualization/score.py
MIT
def get_pitch_classes(fifths: int) -> List[int]: """Return a list of the root note of each pitch number.""" if fifths >= 0: return [0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6] return [0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6]
Return a list of the root note of each pitch number.
get_pitch_classes
python
salu133445/muspy
muspy/visualization/score.py
https://github.com/salu133445/muspy/blob/master/muspy/visualization/score.py
MIT
def get_accidentals(fifths: int) -> List[Optional[int]]: """Return a list of the accidentals and the pitch classes.""" if fifths >= 0: accidentals = [None, 1, None, 1, None, None, 1, None, 1, None, 1, None] if fifths > 0: sharps = [5, 0, 7, 2, 9, 4, 11] for idx in sharps[...
Return a list of the accidentals and the pitch classes.
get_accidentals
python
salu133445/muspy
muspy/visualization/score.py
https://github.com/salu133445/muspy/blob/master/muspy/visualization/score.py
MIT
def set_baseline(self, y): """Set baseline position (y-coordinate of first staff line).""" self._baseline = y self.top = max(self.top, self._baseline) self.bottom = max(self.bottom, self._baseline) self._bottom_note_y = self._baseline self._top_note_y = self._baseline + 4
Set baseline position (y-coordinate of first staff line).
set_baseline
python
salu133445/muspy
muspy/visualization/score.py
https://github.com/salu133445/muspy/blob/master/muspy/visualization/score.py
MIT
def plot_key_signature(self, root: int, mode: str): """Plot a key signature. Supports only major and minor keys.""" # self._accidentals = _get_accidentals(0) # self._pitches = [0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6] # TODO: Support keys other than major and minor keys
Plot a key signature. Supports only major and minor keys.
plot_key_signature
python
salu133445/muspy
muspy/visualization/score.py
https://github.com/salu133445/muspy/blob/master/muspy/visualization/score.py
MIT
def show_score( music: "Music", figsize: Tuple[float, float] = None, clef: str = "treble", clef_octave: int = 0, note_spacing: int = None, font_path: Union[str, Path] = None, font_scale: float = None, ) -> ScorePlotter: """Show score visualization. Parameters ---------- musi...
Show score visualization. Parameters ---------- music : :class:`muspy.Music` Music object to show. figsize : (float, float), optional Width and height in inches. Defaults to Matplotlib configuration. clef : {'treble', 'alto', 'bass'}, default: 'treble' Clef type. ...
show_score
python
salu133445/muspy
muspy/visualization/score.py
https://github.com/salu133445/muspy/blob/master/muspy/visualization/score.py
MIT
def show(music: "Music", kind: str, **kwargs: Any): """Show visualization. Parameters ---------- music : :class:`muspy.Music` Music object to convert. kind : {'piano-roll', 'score'} Target representation. """ if kind.lower() in ("piano-roll", "pianoroll", "piano roll"): ...
Show visualization. Parameters ---------- music : :class:`muspy.Music` Music object to convert. kind : {'piano-roll', 'score'} Target representation.
show
python
salu133445/muspy
muspy/visualization/wrappers.py
https://github.com/salu133445/muspy/blob/master/muspy/visualization/wrappers.py
MIT
def worker(set_percentage, log_text): """ This worker function is called by `progress_dialog`. It will run in a background thread. The `set_percentage` function can be used to update the progress bar, while the `log_text` function can be used to log text in the logging window. """ percentag...
This worker function is called by `progress_dialog`. It will run in a background thread. The `set_percentage` function can be used to update the progress bar, while the `log_text` function can be used to log text in the logging window.
worker
python
prompt-toolkit/python-prompt-toolkit
examples/dialogs/progress_dialog.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/dialogs/progress_dialog.py
BSD-3-Clause
def stop_task(label, total, sleep_time): """Stop at some random index. Breaking out of iteration at some stop index mimics how progress bars behave in cases where errors are raised. """ stop_i = random.randrange(total) bar = pb(range(total), label...
Stop at some random index. Breaking out of iteration at some stop index mimics how progress bars behave in cases where errors are raised.
stop_task
python
prompt-toolkit/python-prompt-toolkit
examples/progress-bar/a-lot-of-parallel-tasks.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/progress-bar/a-lot-of-parallel-tasks.py
BSD-3-Clause
def _(event): """ When space is pressed, we check the word before the cursor, and autocorrect that. """ b = event.app.current_buffer w = b.document.get_word_before_cursor() if w is not None: if w in corrections: b.delete_before_cursor(...
When space is pressed, we check the word before the cursor, and autocorrect that.
_
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/autocorrection.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/autocorrection.py
BSD-3-Clause
def get_prompt(): "Tokens to be shown before the prompt." now = datetime.datetime.now() return [ ("bg:#008800 #ffffff", f"{now.hour}:{now.minute}:{now.second}"), ("bg:cornsilk fg:maroon", " Enter something: "), ]
Tokens to be shown before the prompt.
get_prompt
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/clock-input.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/clock-input.py
BSD-3-Clause
def example_1(): """ Style and list of (style, text) tuples. """ # Not that we can combine class names and inline styles. prompt_fragments = [ ("class:username", "john"), ("class:at", "@"), ("class:host", "localhost"), ("class:colon", ":"), ("class:path", "/us...
Style and list of (style, text) tuples.
example_1
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/colored-prompt.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/colored-prompt.py
BSD-3-Clause
def _(event): """ Print 'hello world' in the terminal when ControlT is pressed. We use ``run_in_terminal``, because that ensures that the prompt is hidden right before ``print_hello`` gets executed and it's drawn again after it. (Otherwise this would destroy the output.) ...
Print 'hello world' in the terminal when ControlT is pressed. We use ``run_in_terminal``, because that ensures that the prompt is hidden right before ``print_hello`` gets executed and it's drawn again after it. (Otherwise this would destroy the output.)
_
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/custom-key-binding.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/custom-key-binding.py
BSD-3-Clause
async def _(event): """ Example of asyncio coroutine as a key binding. """ try: for i in range(5): async with in_terminal(): print("hello") await asyncio.sleep(1) except asyncio.CancelledError: print("Pro...
Example of asyncio coroutine as a key binding.
_
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/custom-key-binding.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/custom-key-binding.py
BSD-3-Clause
def _(event): "A custom text object that involves everything." # Note that a `TextObject` has coordinates, relative to the cursor position. buff = event.current_buffer return TextObject( -buff.document.cursor_position, # The start. len(buff.text) - buff.document....
A custom text object that involves everything.
_
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/custom-vi-operator-and-text-object.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/custom-vi-operator-and-text-object.py
BSD-3-Clause
def get_prompt() -> HTML: """ Build the prompt dynamically every time its rendered. """ left_part = HTML( "<left-part>" " <username>root</username> " " abc " "<path>~/.oh-my-zsh/themes</path>" "</left-part>" ) right_part = HTML( "<right-part> " ...
Build the prompt dynamically every time its rendered.
get_prompt
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/fancy-zsh-prompt.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/fancy-zsh-prompt.py
BSD-3-Clause
def prompt_continuation(width, line_number, wrap_count): """ The continuation: display line numbers and '->' before soft wraps. Notice that we can return any kind of formatted text from here. The prompt continuation doesn't have to be the same width as the prompt which is displayed before the firs...
The continuation: display line numbers and '->' before soft wraps. Notice that we can return any kind of formatted text from here. The prompt continuation doesn't have to be the same width as the prompt which is displayed before the first line, but in this example we choose to align them. The `wi...
prompt_continuation
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/get-multiline-input.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/get-multiline-input.py
BSD-3-Clause
def _(event): "When ControlT has been pressed, toggle visibility." hidden[0] = not hidden[0]
When ControlT has been pressed, toggle visibility.
_
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/get-password-with-toggle-display-shortcut.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/get-password-with-toggle-display-shortcut.py
BSD-3-Clause
def hello_world_window(): """ Create a GTK window with one 'Hello world' button. """ # Create a new window. window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_border_width(50) # Create a new button with the label "Hello World". button = gtk.Button("Hello World") window.add(button) ...
Create a GTK window with one 'Hello world' button.
hello_world_window
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/inputhook.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/inputhook.py
BSD-3-Clause
def inputhook(context): """ When the eventloop of prompt-toolkit is idle, call this inputhook. This will run the GTK main loop until the file descriptor `context.fileno()` becomes ready. :param context: An `InputHookContext` instance. """ def _main_quit(*a, **kw): gtk.main_quit() ...
When the eventloop of prompt-toolkit is idle, call this inputhook. This will run the GTK main loop until the file descriptor `context.fileno()` becomes ready. :param context: An `InputHookContext` instance.
inputhook
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/inputhook.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/inputhook.py
BSD-3-Clause
def _(event): "When ControlT has been pressed, toggle light/dark colors." swapped[0] = not swapped[0]
When ControlT has been pressed, toggle light/dark colors.
_
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/swap-light-and-dark-colors.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/swap-light-and-dark-colors.py
BSD-3-Clause
def _(event): "Toggle between Emacs and Vi mode." if event.app.editing_mode == EditingMode.VI: event.app.editing_mode = EditingMode.EMACS else: event.app.editing_mode = EditingMode.VI
Toggle between Emacs and Vi mode.
_
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/switch-between-vi-emacs.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/switch-between-vi-emacs.py
BSD-3-Clause
def _(event): """ Start auto completion. If the menu is showing already, select the next completion. """ b = event.app.current_buffer if b.complete_state: b.complete_next() else: b.start_completion(select_first=False)
Start auto completion. If the menu is showing already, select the next completion.
_
python
prompt-toolkit/python-prompt-toolkit
examples/prompts/auto-completion/autocomplete-with-control-space.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/auto-completion/autocomplete-with-control-space.py
BSD-3-Clause
async def interact(ssh_session: PromptToolkitSSHSession) -> None: """ The application interaction. This will run automatically in a prompt_toolkit AppSession, which means that any prompt_toolkit application (dialogs, prompts, etc...) will use the SSH channel for input and output. """ prompt...
The application interaction. This will run automatically in a prompt_toolkit AppSession, which means that any prompt_toolkit application (dialogs, prompts, etc...) will use the SSH channel for input and output.
interact
python
prompt-toolkit/python-prompt-toolkit
examples/ssh/asyncssh-server.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/ssh/asyncssh-server.py
BSD-3-Clause
def _send_to_everyone(sender_connection, name, message, color): """ Send a message to all the clients. """ for c in _connections: if c != sender_connection: c.send_above_prompt( [ ("fg:" + color, f"[{name}]"), ("", " "), ...
Send a message to all the clients.
_send_to_everyone
python
prompt-toolkit/python-prompt-toolkit
examples/telnet/chat-app.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/telnet/chat-app.py
BSD-3-Clause
def get_suggestion(self, buffer: Buffer, document: Document) -> Suggestion | None: """ Return `None` or a :class:`.Suggestion` instance. We receive both :class:`~prompt_toolkit.buffer.Buffer` and :class:`~prompt_toolkit.document.Document`. The reason is that auto suggestions are...
Return `None` or a :class:`.Suggestion` instance. We receive both :class:`~prompt_toolkit.buffer.Buffer` and :class:`~prompt_toolkit.document.Document`. The reason is that auto suggestions are retrieved asynchronously. (Like completions.) The buffer text could be changed in the...
get_suggestion
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/auto_suggest.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/auto_suggest.py
BSD-3-Clause
async def get_suggestion_async( self, buff: Buffer, document: Document ) -> Suggestion | None: """ Return a :class:`.Future` which is set when the suggestions are ready. This function can be overloaded in order to provide an asynchronous implementation. """ re...
Return a :class:`.Future` which is set when the suggestions are ready. This function can be overloaded in order to provide an asynchronous implementation.
get_suggestion_async
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/auto_suggest.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/auto_suggest.py
BSD-3-Clause
def go_to_index(self, index: int | None) -> None: """ Create a new :class:`.CompletionState` object with the new index. When `index` is `None` deselect the completion. """ if self.completions: assert index is None or 0 <= index < len(self.completions) sel...
Create a new :class:`.CompletionState` object with the new index. When `index` is `None` deselect the completion.
go_to_index
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def current_completion(self) -> Completion | None: """ Return the current completion, or return `None` when no completion is selected. """ if self.complete_index is not None: return self.completions[self.complete_index] return None
Return the current completion, or return `None` when no completion is selected.
current_completion
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def reset( self, document: Document | None = None, append_to_history: bool = False ) -> None: """ :param append_to_history: Append current input to history first. """ if append_to_history: self.append_to_history() document = document or Document() ...
:param append_to_history: Append current input to history first.
reset
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def load_history_if_not_yet_loaded(self) -> None: """ Create task for populating the buffer history (if not yet done). Note:: This needs to be called from within the event loop of the application, because history loading is async, and we need to be sure the ...
Create task for populating the buffer history (if not yet done). Note:: This needs to be called from within the event loop of the application, because history loading is async, and we need to be sure the right event loop is active. Therefor, we call this method ...
load_history_if_not_yet_loaded
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def load_history_done(f: asyncio.Future[None]) -> None: """ Handle `load_history` result when either done, cancelled, or when an exception was raised. """ try: f.result() except asyncio.CancelledError: ...
Handle `load_history` result when either done, cancelled, or when an exception was raised.
load_history_done
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def _set_text(self, value: str) -> bool: """set text at current working_index. Return whether it changed.""" working_index = self.working_index working_lines = self._working_lines original_value = working_lines[working_index] working_lines[working_index] = value # Retur...
set text at current working_index. Return whether it changed.
_set_text
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def _set_cursor_position(self, value: int) -> bool: """Set cursor position. Return whether it changed.""" original_position = self.__cursor_position self.__cursor_position = max(0, value) return self.__cursor_position != original_position
Set cursor position. Return whether it changed.
_set_cursor_position
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def text(self, value: str) -> None: """ Setting text. (When doing this, make sure that the cursor_position is valid for this text. text/cursor_position should be consistent at any time, otherwise set a Document instead.) """ # Ensure cursor position remains within the siz...
Setting text. (When doing this, make sure that the cursor_position is valid for this text. text/cursor_position should be consistent at any time, otherwise set a Document instead.)
text
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def document(self) -> Document: """ Return :class:`~prompt_toolkit.document.Document` instance from the current text, cursor position and selection state. """ return self._document_cache[ self.text, self.cursor_position, self.selection_state ]
Return :class:`~prompt_toolkit.document.Document` instance from the current text, cursor position and selection state.
document
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def set_document(self, value: Document, bypass_readonly: bool = False) -> None: """ Set :class:`~prompt_toolkit.document.Document` instance. Like the ``document`` property, but accept an ``bypass_readonly`` argument. :param bypass_readonly: When True, don't raise an ...
Set :class:`~prompt_toolkit.document.Document` instance. Like the ``document`` property, but accept an ``bypass_readonly`` argument. :param bypass_readonly: When True, don't raise an :class:`.EditReadOnlyBuffer` exception, even wh...
set_document
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def save_to_undo_stack(self, clear_redo_stack: bool = True) -> None: """ Safe current state (input text and cursor position), so that we can restore it by calling undo. """ # Safe if the text is different from the text at the top of the stack # is different. If the text i...
Safe current state (input text and cursor position), so that we can restore it by calling undo.
save_to_undo_stack
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def transform_lines( self, line_index_iterator: Iterable[int], transform_callback: Callable[[str], str], ) -> str: """ Transforms the text on a range of lines. When the iterator yield an index not in the range of lines that the document contains, it skips them...
Transforms the text on a range of lines. When the iterator yield an index not in the range of lines that the document contains, it skips them silently. To uppercase some lines:: new_text = transform_lines(range(5,10), lambda text: text.upper()) :param line_index_i...
transform_lines
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def transform_current_line(self, transform_callback: Callable[[str], str]) -> None: """ Apply the given transformation function to the current line. :param transform_callback: callable that takes a string and return a new string. """ document = self.document a = document...
Apply the given transformation function to the current line. :param transform_callback: callable that takes a string and return a new string.
transform_current_line
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def transform_region( self, from_: int, to: int, transform_callback: Callable[[str], str] ) -> None: """ Transform a part of the input string. :param from_: (int) start position. :param to: (int) end position. :param transform_callback: Callable which accepts a strin...
Transform a part of the input string. :param from_: (int) start position. :param to: (int) end position. :param transform_callback: Callable which accepts a string and returns the transformed string.
transform_region
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def cursor_up(self, count: int = 1) -> None: """(for multiline edit). Move cursor to the previous line.""" original_column = self.preferred_column or self.document.cursor_position_col self.cursor_position += self.document.get_cursor_up_position( count=count, preferred_column=original...
(for multiline edit). Move cursor to the previous line.
cursor_up
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def cursor_down(self, count: int = 1) -> None: """(for multiline edit). Move cursor to the next line.""" original_column = self.preferred_column or self.document.cursor_position_col self.cursor_position += self.document.get_cursor_down_position( count=count, preferred_column=original...
(for multiline edit). Move cursor to the next line.
cursor_down
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def auto_up( self, count: int = 1, go_to_start_of_line_if_history_changes: bool = False ) -> None: """ If we're not on the first line (of a multiline input) go a line up, otherwise go back in history. (If nothing is selected.) """ if self.complete_state: s...
If we're not on the first line (of a multiline input) go a line up, otherwise go back in history. (If nothing is selected.)
auto_up
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def auto_down( self, count: int = 1, go_to_start_of_line_if_history_changes: bool = False ) -> None: """ If we're not on the last line (of a multiline input) go a line down, otherwise go forward in history. (If nothing is selected.) """ if self.complete_state: ...
If we're not on the last line (of a multiline input) go a line down, otherwise go forward in history. (If nothing is selected.)
auto_down
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def delete_before_cursor(self, count: int = 1) -> str: """ Delete specified number of characters before cursor and return the deleted text. """ assert count >= 0 deleted = "" if self.cursor_position > 0: deleted = self.text[self.cursor_position - coun...
Delete specified number of characters before cursor and return the deleted text.
delete_before_cursor
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def delete(self, count: int = 1) -> str: """ Delete specified number of characters and Return the deleted text. """ if self.cursor_position < len(self.text): deleted = self.document.text_after_cursor[:count] self.text = ( self.text[: self.cursor_po...
Delete specified number of characters and Return the deleted text.
delete
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause
def join_next_line(self, separator: str = " ") -> None: """ Join the next line to the current one by deleting the line ending after the current line. """ if not self.document.on_last_line: self.cursor_position += self.document.get_end_of_line_position() se...
Join the next line to the current one by deleting the line ending after the current line.
join_next_line
python
prompt-toolkit/python-prompt-toolkit
src/prompt_toolkit/buffer.py
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/buffer.py
BSD-3-Clause