Source

Kephra / lib / Kephra / Edit / Comment.pm

Full commit
use strict;
use warnings;

use Kephra::API;

#package Kephra::Edit::Comment;
package Kephra::App::Editor;

Kephra::API::Command::register({
 'edit-comment-toggle'=>{sub=>'$ed->toggle_comment', label=>'Toggle Comment', keys=>'alt+#' },
});

my $delimiter = '#';

sub comment {
	my ($self) = @_;
	my ($start, $end) = $self->GetSelection;
	my $line_sel = [ $self->LineFromPosition($start), $self->LineFromPosition($end) ];

	$self->BeginUndoAction;
	for ($line_sel->[0] .. $line_sel->[1]) {
		my $ipos = $self->GetLineIndentPosition($_);
		next if $ipos == $self->GetLineEndPosition($_);
		$self->InsertText($ipos, '#') unless $self->GetCharAt( $ipos ) == ord '#';
	}
	$self->SetSelection( 
		$self->PositionFromLine(  $line_sel->[0] ),
		$self->GetLineEndPosition($line_sel->[1] )
	);
	$self->EndUndoAction;
}

sub decomment {
	my ($self) = @_;
	my ($start, $end) = $self->GetSelection;
	my $line_sel = [ $self->LineFromPosition($start), $self->LineFromPosition($end) ];

	$self->BeginUndoAction;
	for ($line_sel->[0] .. $line_sel->[1]) {
		my $ipos = $self->GetLineIndentPosition($_);
		if ($self->GetCharAt( $ipos ) eq ord '#') {
			$self->SetTargetStart($ipos);
			$self->SetTargetEnd($ipos+1);
			$self->ReplaceTarget('');
		}
	}
	$self->SetSelection( 
		$self->PositionFromLine(  $line_sel->[0] ),
		$self->GetLineEndPosition($line_sel->[1] )
	);
	$self->EndUndoAction;
}

sub toggle_comment {
	my ($self) = @_;
	$self->GetCharAt( $self->GetLineIndentPosition( 
		$self->LineFromPosition ($self->GetSelectionStart)) ) eq ord '#'
			? decomment(@_)
			:   comment(@_);
}


1;