GNU bug report logs - #60128
30.0.50; [PATCH]: Add treesit-transpose-sexps

Please note: This is a static page, with minimal formatting, updated once a day.
Click here to see this page with the latest information and nicer formatting.

Package: emacs; Reported by: Theodor Thornhill <theo@HIDDEN>; Keywords: patch; dated Fri, 16 Dec 2022 20:05:01 UTC; Maintainer for emacs is bug-gnu-emacs@HIDDEN.

Message received at 60128 <at> debbugs.gnu.org:


Received: (at 60128) by debbugs.gnu.org; 7 Jan 2023 23:18:25 +0000
From debbugs-submit-bounces <at> debbugs.gnu.org Sat Jan 07 18:18:25 2023
Received: from localhost ([127.0.0.1]:59269 helo=debbugs.gnu.org)
	by debbugs.gnu.org with esmtp (Exim 4.84_2)
	(envelope-from <debbugs-submit-bounces <at> debbugs.gnu.org>)
	id 1pEISG-0001WA-VQ
	for submit <at> debbugs.gnu.org; Sat, 07 Jan 2023 18:18:25 -0500
Received: from mail-pj1-f51.google.com ([209.85.216.51]:43771)
 by debbugs.gnu.org with esmtp (Exim 4.84_2)
 (envelope-from <casouri@HIDDEN>) id 1pEISF-0001Vs-Np
 for 60128 <at> debbugs.gnu.org; Sat, 07 Jan 2023 18:18:24 -0500
Received: by mail-pj1-f51.google.com with SMTP id
 b9-20020a17090a7ac900b00226ef160dcaso3799478pjl.2
 for <60128 <at> debbugs.gnu.org>; Sat, 07 Jan 2023 15:18:23 -0800 (PST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112;
 h=to:cc:date:message-id:subject:mime-version
 :content-transfer-encoding:from:from:to:cc:subject:date:message-id
 :reply-to; bh=4mr6ab59wjimaByh93eTNBWR6iZs3+0Lbhwaz5t93BM=;
 b=azbIlmojbqVfIrvDEg3lxgVhHealGIrJ3GISj7DFcu3CFVNQS0YymiM8aHuVsNxb53
 0vxKuK3FJnNm+tSX+jTa1OWgc3Hc9nh/bCjypp9B9s+zVbi7VL8EhXvydbeIjl/UsxRx
 tNPp+Vm4OS6HAynHVBcaSt9sXUjE0NMkeDxwj1mja4r5eKKcFd3itLC0noeyCCqH+9zM
 vj962uc2HICZOq55CRyzS/Qzg989R9MMLxBVi6FNtGDlAowYMpFb80mxpf3ccRr+sKeH
 HvEV4x2noRvspm9cx+hj9fHXUaHzLuDGCBbgkJLvj5m+d2bYdzBXYyQ8qmfQhAB8wvQ2
 W+3w==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
 d=1e100.net; s=20210112;
 h=to:cc:date:message-id:subject:mime-version
 :content-transfer-encoding:from:x-gm-message-state:from:to:cc
 :subject:date:message-id:reply-to;
 bh=4mr6ab59wjimaByh93eTNBWR6iZs3+0Lbhwaz5t93BM=;
 b=BuwhviT7SvK7eZlF5vp1Kdh2K13DCeNwJSaLGpriWlAAO0OxoH1lT3sYQOTP7iJwEe
 oMWxCBMsSBVPKALJ9Roa56FIxXaLgllVpviHAG251l4IiQXEN7aC/vgXQryUfcEh594d
 oO74u71bEqwcjL/Ze8r/SJdc9umBmjThhpJKJlsjPLNQ8ClzB7WuZERmKehHLAifnhl8
 aWkxs32VRjYXputmhh3XyAdRx6TsJzkr0a9sj0+ORfnxS4ovmfwlk8B/IRb37G2PuYlM
 827tklQp6MUQwXmr6nSrgiX3i6RbGv9y6ZP1kCmykdlH4u4BXIhvTdtZOffbkqJV4QGE
 /TcA==
X-Gm-Message-State: AFqh2koqc88pP0ZubJ3woARzkgHoCisHH5McWscKV3vAb8RQ0mH/NSnZ
 fNwr/4Xue9LrC6CyEd0RrFFEH4MqNERINw==
X-Google-Smtp-Source: AMrXdXt7g7IJeOeiMqCIYpJy6+V0vnh0hh72QGvTm7idp0YpcwOkPrcWXK6f3nR4PJ5hl0LY3n2dHA==
X-Received: by 2002:a17:90a:6a4f:b0:226:ed1b:c7b7 with SMTP id
 d15-20020a17090a6a4f00b00226ed1bc7b7mr4263380pjm.13.1673133498121; 
 Sat, 07 Jan 2023 15:18:18 -0800 (PST)
Received: from smtpclient.apple (cpe-172-117-161-177.socal.res.rr.com.
 [172.117.161.177]) by smtp.gmail.com with ESMTPSA id
 az7-20020a17090b028700b00225e670e4c7sm2946254pjb.35.2023.01.07.15.18.17
 (version=TLS1_2 cipher=ECDHE-ECDSA-AES128-GCM-SHA256 bits=128/128);
 Sat, 07 Jan 2023 15:18:17 -0800 (PST)
From: Yuan Fu <casouri@HIDDEN>
Content-Type: text/plain;
	charset=utf-8
Content-Transfer-Encoding: quoted-printable
Mime-Version: 1.0 (Mac OS X Mail 16.0 \(3696.120.41.1.1\))
Subject: Re: bug#60128: 30.0.50; [PATCH]: Add treesit-transpose-sexps
Message-Id: <7D26601B-034E-4DD1-9358-FC31C0EBCB26@HIDDEN>
Date: Sat, 7 Jan 2023 15:18:17 -0800
To: Eli Zaretskii <eliz@HIDDEN>
X-Mailer: Apple Mail (2.3696.120.41.1.1)
X-Spam-Score: 0.0 (/)
X-Debbugs-Envelope-To: 60128
Cc: 60128 <at> debbugs.gnu.org, Theodor Thornhill <theo@HIDDEN>,
 monnier@HIDDEN
X-BeenThere: debbugs-submit <at> debbugs.gnu.org
X-Mailman-Version: 2.1.18
Precedence: list
List-Id: <debbugs-submit.debbugs.gnu.org>
List-Unsubscribe: <https://debbugs.gnu.org/cgi-bin/mailman/options/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=unsubscribe>
List-Archive: <https://debbugs.gnu.org/cgi-bin/mailman/private/debbugs-submit/>
List-Post: <mailto:debbugs-submit <at> debbugs.gnu.org>
List-Help: <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=help>
List-Subscribe: <https://debbugs.gnu.org/cgi-bin/mailman/listinfo/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=subscribe>
Errors-To: debbugs-submit-bounces <at> debbugs.gnu.org
Sender: "Debbugs-submit" <debbugs-submit-bounces <at> debbugs.gnu.org>
X-Spam-Score: -1.0 (-)


Eli Zaretskii <eliz@HIDDEN> writes:

>> From: Theodor Thornhill <theo@HIDDEN>
>> Cc: casouri@HIDDEN,  Stefan Monnier <monnier@HIDDEN>, =
eliz@HIDDEN
>> Date: Mon, 26 Dec 2022 21:53:57 +0100
>>=20
>> Eli, does this require a NEWS entry or more documentation?
>
> A NEWS entry should be enough.

IIRC this is pushed to master right? If so I=E2=80=99ll close this.

Yuan




Information forwarded to bug-gnu-emacs@HIDDEN:
bug#60128; Package emacs. Full text available.

Message received at 60128 <at> debbugs.gnu.org:


Received: (at 60128) by debbugs.gnu.org; 27 Dec 2022 11:56:40 +0000
From debbugs-submit-bounces <at> debbugs.gnu.org Tue Dec 27 06:56:40 2022
Received: from localhost ([127.0.0.1]:54844 helo=debbugs.gnu.org)
	by debbugs.gnu.org with esmtp (Exim 4.84_2)
	(envelope-from <debbugs-submit-bounces <at> debbugs.gnu.org>)
	id 1pA8ZU-0000B2-7P
	for submit <at> debbugs.gnu.org; Tue, 27 Dec 2022 06:56:40 -0500
Received: from eggs.gnu.org ([209.51.188.92]:38698)
 by debbugs.gnu.org with esmtp (Exim 4.84_2)
 (envelope-from <eliz@HIDDEN>) id 1pA8ZT-0000Ao-29
 for 60128 <at> debbugs.gnu.org; Tue, 27 Dec 2022 06:56:39 -0500
Received: from fencepost.gnu.org ([2001:470:142:3::e])
 by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256)
 (Exim 4.90_1) (envelope-from <eliz@HIDDEN>)
 id 1pA8ZM-00076D-8g; Tue, 27 Dec 2022 06:56:32 -0500
DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=gnu.org;
 s=fencepost-gnu-org; h=References:Subject:In-Reply-To:To:From:Date:
 mime-version; bh=8QrpGMSrTQOjq93D2+vmIxMkedHTyF6GvzPE92wtyeY=; b=L71tK/zpOUim
 sd0cn3gUzhtjOUpthZZ9DUZmTqSAN8D4VucBEZ7xuxuSgypB8B53lXvURFIbApPMI2f0aqoHN/Njk
 Uvx0Tz/a0T3zCEOSEsnH8deB7n+KmBqvwJBJFC+qNStukEDvUWQqFhY04UbHACBjYzc9KsQzfRsZA
 3dw7ijDSU2VQoXxnzu5fq5IIGal1joMEyExmqptl28TTjM8Lgb18mrhfvfIhWqzcK2/LtXtgU8/nw
 rjRnnJ4HP1juCaa/OTfBlDwivSibPr1AqAWC0UvD6xhzaDXKNO72iHTAH4UPuPk/dYA/6HD5k3YaY
 6Oc8JnCXK8+43bOHSqkDIQ==;
Received: from [87.69.77.57] (helo=home-c4e4a596f7)
 by fencepost.gnu.org with esmtpsa (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256)
 (Exim 4.90_1) (envelope-from <eliz@HIDDEN>)
 id 1pA8ZL-0006xh-MF; Tue, 27 Dec 2022 06:56:32 -0500
Date: Tue, 27 Dec 2022 13:56:37 +0200
Message-Id: <83zgb912mi.fsf@HIDDEN>
From: Eli Zaretskii <eliz@HIDDEN>
To: Theodor Thornhill <theo@HIDDEN>
In-Reply-To: <873591honu.fsf@HIDDEN> (message from Theodor Thornhill on
 Mon, 26 Dec 2022 21:53:57 +0100)
Subject: Re: bug#60128: 30.0.50; [PATCH]: Add treesit-transpose-sexps
References: <87a63nru7n.fsf@HIDDEN> <87edsytcoh.fsf@HIDDEN>
 <873591honu.fsf@HIDDEN>
X-Spam-Score: -2.3 (--)
X-Debbugs-Envelope-To: 60128
Cc: 60128 <at> debbugs.gnu.org, casouri@HIDDEN, monnier@HIDDEN
X-BeenThere: debbugs-submit <at> debbugs.gnu.org
X-Mailman-Version: 2.1.18
Precedence: list
List-Id: <debbugs-submit.debbugs.gnu.org>
List-Unsubscribe: <https://debbugs.gnu.org/cgi-bin/mailman/options/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=unsubscribe>
List-Archive: <https://debbugs.gnu.org/cgi-bin/mailman/private/debbugs-submit/>
List-Post: <mailto:debbugs-submit <at> debbugs.gnu.org>
List-Help: <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=help>
List-Subscribe: <https://debbugs.gnu.org/cgi-bin/mailman/listinfo/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=subscribe>
Errors-To: debbugs-submit-bounces <at> debbugs.gnu.org
Sender: "Debbugs-submit" <debbugs-submit-bounces <at> debbugs.gnu.org>
X-Spam-Score: -3.3 (---)

> From: Theodor Thornhill <theo@HIDDEN>
> Cc: casouri@HIDDEN,  Stefan Monnier <monnier@HIDDEN>, eliz@HIDDEN
> Date: Mon, 26 Dec 2022 21:53:57 +0100
> 
> Eli, does this require a NEWS entry or more documentation?

A NEWS entry should be enough.




Information forwarded to bug-gnu-emacs@HIDDEN:
bug#60128; Package emacs. Full text available.

Message received at 60128 <at> debbugs.gnu.org:


Received: (at 60128) by debbugs.gnu.org; 26 Dec 2022 22:37:49 +0000
From debbugs-submit-bounces <at> debbugs.gnu.org Mon Dec 26 17:37:49 2022
Received: from localhost ([127.0.0.1]:54319 helo=debbugs.gnu.org)
	by debbugs.gnu.org with esmtp (Exim 4.84_2)
	(envelope-from <debbugs-submit-bounces <at> debbugs.gnu.org>)
	id 1p9w6O-0004dR-9y
	for submit <at> debbugs.gnu.org; Mon, 26 Dec 2022 17:37:48 -0500
Received: from out-161.mta0.migadu.com ([91.218.175.161]:58424)
 by debbugs.gnu.org with esmtp (Exim 4.84_2)
 (envelope-from <theo@HIDDEN>) id 1p9w6I-0004dE-G3
 for 60128 <at> debbugs.gnu.org; Mon, 26 Dec 2022 17:37:47 -0500
X-Report-Abuse: Please report any abuse attempt to abuse@HIDDEN and
 include these headers.
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=thornhill.no;
 s=key1; t=1672094261;
 h=from:from:reply-to:subject:subject:date:date:message-id:message-id:
 to:to:cc:cc:mime-version:mime-version:content-type:content-type:
 in-reply-to:in-reply-to:references:references;
 bh=7l17f3nPeougVoEJ+eTV4fo5IbsRS1+G0buVl4xl+eY=;
 b=fhEKPdXitqR4dmVS3JnwsUE2ujBX1UsJOKUMUtuwiyYN2PEtjzCj4ueLc82eS8pgRt7PhB
 6RDPf8Kct9OIuQytJr3UQYutsix/vyvZzcfEofzTvCCKWqQf/dh2nEbOC9CPVVI3Og6Gya
 I/2SQcSf+fRi9tX53Og7rKuXsW+XcSrky8aF8siahaGfMf145ZgObqGmnm9BUV/Ku+Xnkw
 WUCFiZA1dl0bb4N2kD1K0bMYC1715X5A7owKA+NCFcW341zpBABV0tzVKqMwBDzenVczEm
 HeT8BwJtQndRko2tWzOWkMncMwnBrMdKPdmDh4FijWgbbURlh696fFrEhncSRg==
From: Theodor Thornhill <theo@HIDDEN>
To: Yuan Fu <casouri@HIDDEN>
Subject: Re: bug#60128: 30.0.50; [PATCH]: Add treesit-transpose-sexps
In-Reply-To: <0D9F1198-B5FB-451D-B0E8-DB22910DAB58@HIDDEN>
References: <87a63nru7n.fsf@HIDDEN> <87edsytcoh.fsf@HIDDEN>
 <873591honu.fsf@HIDDEN>
 <0D9F1198-B5FB-451D-B0E8-DB22910DAB58@HIDDEN>
Date: Mon, 26 Dec 2022 23:37:40 +0100
Message-ID: <87wn6dg5aj.fsf@HIDDEN>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="=-=-="
X-Migadu-Flow: FLOW_OUT
X-Spam-Score: 0.0 (/)
X-Debbugs-Envelope-To: 60128
Cc: 60128 <at> debbugs.gnu.org, eliz@HIDDEN,
 Stefan Monnier <monnier@HIDDEN>
X-BeenThere: debbugs-submit <at> debbugs.gnu.org
X-Mailman-Version: 2.1.18
Precedence: list
List-Id: <debbugs-submit.debbugs.gnu.org>
List-Unsubscribe: <https://debbugs.gnu.org/cgi-bin/mailman/options/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=unsubscribe>
List-Archive: <https://debbugs.gnu.org/cgi-bin/mailman/private/debbugs-submit/>
List-Post: <mailto:debbugs-submit <at> debbugs.gnu.org>
List-Help: <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=help>
List-Subscribe: <https://debbugs.gnu.org/cgi-bin/mailman/listinfo/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=subscribe>
Errors-To: debbugs-submit-bounces <at> debbugs.gnu.org
Sender: "Debbugs-submit" <debbugs-submit-bounces <at> debbugs.gnu.org>
X-Spam-Score: -1.0 (-)

--=-=-=
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

Yuan Fu <casouri@HIDDEN> writes:

>> On Dec 26, 2022, at 12:53 PM, Theodor Thornhill <theo@HIDDEN> wrot=
e:
>>=20
>> Theodor Thornhill <theo@HIDDEN> writes:
>>=20
>>> Theodor Thornhill <theo@HIDDEN> writes:
>>>=20
>>>> Hi there!
>>>>=20
>>>> Attached is a patch that enables transpose-sexps for tree-sitter enabl=
ed
>>>> modes.
>>>>=20
>>>> This function will swap the node _before_ node-at-point with the node
>>>> _after_, so it would do something like:
>>>>=20
>>>>       foo a|nd bar =3D> bar and foo|
>>>>=20
>>>> or
>>>>       foo(a + 4,| y + c * b, b, d); =3D> foo(y + c * b, a + 4|, b, d);
>>>>=20
>>>> It will _not_ try to swap things that are not siblings.  I think that
>>>> makes sense in the case of non-lisp languages, since _most_ places you
>>>> can transpose-sexps you will end up with broken code.
>>>>=20
>>>=20
>>> from 'transpose-subr-1':
>>>=20
>>>  (if (> (cdr pos1) (car pos2)) (error "Don't have two things to
>>>  transpose"))
>>>=20
>>> I added this hack into the function in the patch, but I think that
>>> triggering an error is too much.
>>>=20
>>>    ;; Hack to trigger the error message in `transpose-subr-1' when we
>>>    ;; don't have siblings to swap.
>>>    (list (cons 0 1) (cons 0 1))))
>>>=20
>>> I guess I could just follow suit in my function and do like in the
>>> following patch:
>>>=20
>>> Theo
>>=20
>>=20
>> Considering there is both a bug-report _and_ a discussion around this I
>> guess the best idea is to add the patch to this bug report, and continue
>> discussing this in the report rather than emacs-devel?
>>=20
>> What do you think about this patch?
>>=20
>> (copied from emacs-devel):
>> It feels a little iffy how to handle the separate return values, but it
>> works.  I'd be super happy for some feedback on how to best solve that,
>> though :)
>
> By separate return values, do you mean the function returns a cons of
> cons? It seems fine to me. Though I think the docstring could be more
> specific. Like saying return a cons (REGION . REGION), where REGION is
> (BEG . END), where BEG and END...
>

I updated the patch adressing your comment.  The current "protocol" used
on the master branch implies that the regions are calculated by actually
moving inside the buffer and running (point).  Because we don't need
that with the ast in hand I'm trying to support a new protocol, where we
just supply the data we need.  It's a little difficult to "surgically"
modify the behavior, so I'm very open to suggestions, but I believe it
should work properly as the patch stands.

>>=20
>> Also, I made the treesit-transpose-sexps a little better imo, in that we
>> only find named nodes to swap, but use every available node for the
>> entry. We rarely, if ever want to swap the unnamed nodes.
>>=20
>> Eli, does this require a NEWS entry or more documentation?
>
> IMHO a backend/helper function shouldn=E2=80=99t signal a user-error, it=
=E2=80=99s
> better to return nil and let the command to signal errors.

Yeah, I agree.  Adjusted the patch.  Let me know what you think!

Theo


--=-=-=
Content-Type: text/x-diff
Content-Disposition: attachment;
 filename=0001-Add-treesit-transpose-sexps-bug-60128.patch

From 74a7980758b929c991e317ea281b7cd4a097fdff Mon Sep 17 00:00:00 2001
From: Theodor Thornhill <theo@HIDDEN>
Date: Sun, 25 Dec 2022 20:11:59 +0100
Subject: [PATCH] Add treesit-transpose-sexps (bug#60128)

We don't really need to rely on forward-sexp to define what to
transpose.  In tree-sitter we can consider siblings as "balanced
expressions", and swap them without doing any movement to calculate
where the siblings in question are.

* lisp/simple.el (transpose-sexps-function): New defvar-local.
(transpose-sexps): Use the new defvar-local if available.
(transpose-subr): Check whether the mover function returns a cons of
conses, then run transpose-subr-1 on the position-pairs.
* lisp/treesit.el (treesit-transpose-sexps): New function.
---
 lisp/simple.el  | 106 +++++++++++++++++++++++++++++-------------------
 lisp/treesit.el |  28 ++++++++++++-
 2 files changed, 91 insertions(+), 43 deletions(-)

diff --git a/lisp/simple.el b/lisp/simple.el
index 4551b749d5..99dbfaea9f 100644
--- a/lisp/simple.el
+++ b/lisp/simple.el
@@ -8438,6 +8438,21 @@ transpose-words
   (interactive "*p")
   (transpose-subr 'forward-word arg))
 
+(defvar-local transpose-sexps-function nil
+  "If non-nil, `transpose-sexps' delegates to this function.
+
+This function takes one argument ARG, a number as provided
+through running `transpose-sexps'.  It supports the following two
+return values:
+
+1. A cons (REGION . REGION), where REGION is (BEG . END) and BEG
+and END are buffer positions.
+
+2. A cons (BEG . END), where BEG and END are buffer positions.
+
+If the second return value is chosen for this function, it is
+expected to behave similarly to `forward-sexp' and friends.")
+
 (defun transpose-sexps (arg &optional interactive)
   "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
 Unlike `transpose-words', point must be between the two sexps and not
@@ -8454,36 +8469,37 @@ transpose-sexps
           (transpose-sexps arg nil)
         (scan-error (user-error "Not between two complete sexps")))
     (transpose-subr
-     (lambda (arg)
-       ;; Here we should try to simulate the behavior of
-       ;; (cons (progn (forward-sexp x) (point))
-       ;;       (progn (forward-sexp (- x)) (point)))
-       ;; Except that we don't want to rely on the second forward-sexp
-       ;; putting us back to where we want to be, since forward-sexp-function
-       ;; might do funny things like infix-precedence.
-       (if (if (> arg 0)
-	       (looking-at "\\sw\\|\\s_")
-	     (and (not (bobp))
-		  (save-excursion
-                    (forward-char -1)
-                    (looking-at "\\sw\\|\\s_"))))
-	   ;; Jumping over a symbol.  We might be inside it, mind you.
-	   (progn (funcall (if (> arg 0)
-			       'skip-syntax-backward 'skip-syntax-forward)
-			   "w_")
-		  (cons (save-excursion (forward-sexp arg) (point)) (point)))
-         ;; Otherwise, we're between sexps.  Take a step back before jumping
-         ;; to make sure we'll obey the same precedence no matter which
-         ;; direction we're going.
-         (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward)
-                  " .")
-         (cons (save-excursion (forward-sexp arg) (point))
-	       (progn (while (or (forward-comment (if (> arg 0) 1 -1))
-			         (not (zerop (funcall (if (> arg 0)
-							  'skip-syntax-forward
-						        'skip-syntax-backward)
-						      ".")))))
-		      (point)))))
+     (if transpose-sexps-function transpose-sexps-function
+       (lambda (arg)
+         ;; Here we should try to simulate the behavior of
+         ;; (cons (progn (forward-sexp x) (point))
+         ;;       (progn (forward-sexp (- x)) (point)))
+         ;; Except that we don't want to rely on the second forward-sexp
+         ;; putting us back to where we want to be, since forward-sexp-function
+         ;; might do funny things like infix-precedence.
+         (if (if (> arg 0)
+	         (looking-at "\\sw\\|\\s_")
+	       (and (not (bobp))
+	            (save-excursion
+                      (forward-char -1)
+                      (looking-at "\\sw\\|\\s_"))))
+             ;; Jumping over a symbol.  We might be inside it, mind you.
+	     (progn (funcall (if (> arg 0)
+			         #'skip-syntax-backward #'skip-syntax-forward)
+			     "w_")
+	            (cons (save-excursion (forward-sexp arg) (point)) (point)))
+           ;; Otherwise, we're between sexps.  Take a step back before jumping
+           ;; to make sure we'll obey the same precedence no matter which
+           ;; direction we're going.
+           (funcall (if (> arg 0) #'skip-syntax-backward #'skip-syntax-forward)
+                    " .")
+           (cons (save-excursion (forward-sexp arg) (point))
+	         (progn (while (or (forward-comment (if (> arg 0) 1 -1))
+			           (not (zerop (funcall (if (> arg 0)
+						            #'skip-syntax-forward
+						          #'skip-syntax-backward)
+						        ".")))))
+		        (point))))))
      arg 'special)))
 
 (defun transpose-lines (arg)
@@ -8509,19 +8525,23 @@ transpose-lines
 ;; FIXME document SPECIAL.
 (defun transpose-subr (mover arg &optional special)
   "Subroutine to do the work of transposing objects.
-Works for lines, sentences, paragraphs, etc.  MOVER is a function that
-moves forward by units of the given object (e.g. `forward-sentence',
-`forward-paragraph').  If ARG is zero, exchanges the current object
-with the one containing mark.  If ARG is an integer, moves the
-current object past ARG following (if ARG is positive) or
-preceding (if ARG is negative) objects, leaving point after the
-current object."
-  (let ((aux (if special mover
-	       (lambda (x)
-		 (cons (progn (funcall mover x) (point))
-		       (progn (funcall mover (- x)) (point))))))
-	pos1 pos2)
+Works for lines, sentences, paragraphs, etc.  MOVER is either a
+function that moves forward by units of the given
+object (e.g. `forward-sentence', `forward-paragraph'), or a
+function that calculates a cons of two position-pairs.  If ARG is
+zero, exchanges the current object with the one containing mark.
+If ARG is an integer, moves the current object past ARG
+following (if ARG is positive) or preceding (if ARG is negative)
+objects, leaving point after the current object."
+  (let* ((aux (if special mover
+	        (lambda (x)
+		  (cons (progn (funcall mover x) (point))
+		        (progn (funcall mover (- x)) (point))))))
+	 (pos1 (save-excursion (funcall aux arg)))
+         pos2)
     (cond
+     ((and (consp (car pos1)) (consp (cdr pos1)))
+      (transpose-subr-1 (car pos1) (cdr pos1)))
      ((= arg 0)
       (save-excursion
 	(setq pos1 (funcall aux 1))
@@ -8542,6 +8562,8 @@ transpose-subr
       (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
 
 (defun transpose-subr-1 (pos1 pos2)
+  (unless (and pos1 pos2)
+    (error "Don't have two things to transpose"))
   (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
   (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
   (when (> (car pos1) (car pos2))
diff --git a/lisp/treesit.el b/lisp/treesit.el
index cefbed1a16..2bd7f71f2f 100644
--- a/lisp/treesit.el
+++ b/lisp/treesit.el
@@ -1582,6 +1582,31 @@ treesit-search-forward-goto
       (goto-char current-pos)))
     node))
 
+(defun treesit-transpose-sexps (&optional arg)
+  "Tree-sitter `transpose-sexps' function.
+Arg is the same as in `transpose-sexps'.
+
+Locate the node closest to POINT, and transpose that node with
+its sibling node ARG nodes away.
+
+Return a pair of positions as described by
+`transpose-sexps-function' for use in `transpose-subr' and
+friends."
+  (let* ((parent (treesit-node-parent (treesit-node-at (point))))
+         (child (treesit-node-child parent 0 t)))
+    (named-let loop ((prev child)
+                     (next (treesit-node-child
+                            parent (+ arg (treesit-node-index child t))
+                            t)))
+      (when (and prev next)
+        (if (< (point) (treesit-node-end next))
+            (cons (cons (treesit-node-start prev)
+                        (treesit-node-end prev))
+                  (cons (treesit-node-start next)
+                        (treesit-node-end next)))
+          (loop (treesit-node-next-sibling prev t)
+                (treesit-node-next-sibling next t)))))))
+
 ;;; Navigation, defun, things
 ;;
 ;; Emacs lets you define "things" by a regexp that matches the type of
@@ -2111,7 +2136,8 @@ treesit-major-mode-setup
   ;; Defun name.
   (when treesit-defun-name-function
     (setq-local add-log-current-defun-function
-                #'treesit-add-log-current-defun)))
+                #'treesit-add-log-current-defun))
+  (setq-local transpose-sexps-function #'treesit-transpose-sexps))
 
 ;;; Debugging
 
-- 
2.34.1


--=-=-=--




Information forwarded to bug-gnu-emacs@HIDDEN:
bug#60128; Package emacs. Full text available.

Message received at 60128 <at> debbugs.gnu.org:


Received: (at 60128) by debbugs.gnu.org; 26 Dec 2022 21:27:07 +0000
From debbugs-submit-bounces <at> debbugs.gnu.org Mon Dec 26 16:27:07 2022
Received: from localhost ([127.0.0.1]:54260 helo=debbugs.gnu.org)
	by debbugs.gnu.org with esmtp (Exim 4.84_2)
	(envelope-from <debbugs-submit-bounces <at> debbugs.gnu.org>)
	id 1p9uzz-0002hg-3Y
	for submit <at> debbugs.gnu.org; Mon, 26 Dec 2022 16:27:07 -0500
Received: from mail-pj1-f42.google.com ([209.85.216.42]:40638)
 by debbugs.gnu.org with esmtp (Exim 4.84_2)
 (envelope-from <casouri@HIDDEN>) id 1p9uzu-0002h7-V2
 for 60128 <at> debbugs.gnu.org; Mon, 26 Dec 2022 16:27:05 -0500
Received: by mail-pj1-f42.google.com with SMTP id
 c8-20020a17090a4d0800b00225c3614161so8445121pjg.5
 for <60128 <at> debbugs.gnu.org>; Mon, 26 Dec 2022 13:27:02 -0800 (PST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112;
 h=to:references:message-id:content-transfer-encoding:cc:date
 :in-reply-to:from:subject:mime-version:from:to:cc:subject:date
 :message-id:reply-to;
 bh=NAVMBJQpYm7cNEc4854yeykl1mCf0Io7FFJc7Cq7okI=;
 b=htCgzk7CsISnWzR8SP8qCBhouyxrvea/WAArZSCQwq7f66fJm7FfZChZDE95pnhsiI
 OWBkRfvYyeEu2bQkIsStJMJmJgSCc6I1e6RK88U3QeIeKz0hfd9M4nBjQgFfR4VLon4S
 wVBYLdqjUml5869nkOw9gcOAMl3g7nqQeqLtuGjfmTbQOVIVVIshwKh09Aif9LFL1sdh
 zw1wgIEw3a6mFbHX0i7xXzijjf6G99Wt3iXlPQ4AMJ5fdysMn55bAVNnAAQNKhSDAF+z
 zETouI47Av0TxQzLbnmumn6lcFvKGZbUjEjAclFv8hK61e7lGkuB6/SIVZw/uY/Sa+xX
 doNQ==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
 d=1e100.net; s=20210112;
 h=to:references:message-id:content-transfer-encoding:cc:date
 :in-reply-to:from:subject:mime-version:x-gm-message-state:from:to:cc
 :subject:date:message-id:reply-to;
 bh=NAVMBJQpYm7cNEc4854yeykl1mCf0Io7FFJc7Cq7okI=;
 b=nmLtF1UcGzFLDAssNefhxoNbSP2SjJkYpVVXe6lsEYaTPIF5oikJIMsJ36APLMJjFp
 5GHp6LM0v1KhsGnK9UMvnJkBlrRX2099KD5UGzW3bL8pq9jjc0Vwra1KBzdyGlydm5Hs
 yVeHUzsSq9mQ5Bh6bI2DLmIV0243Rwk2omx2SXREECVk/fABgNGDvWZs+Fh1gWgifYjy
 z4NunfT05P2rZUvcPUB4EUF/mUPMKLr5tXzNerQ6dTtXzKF+eRGPnmBkxc/y7fwFdytB
 kwfXAjByXRs5mdL5OO4nOlLgM2qKXEQxL0dEoRa3cgO8c8rWYSoECNeFBeYj0NI/LqtW
 W3og==
X-Gm-Message-State: AFqh2krKg8hfO3Sv/Nq9nX8DTqZ9iaQ2JXzdZn/jQhI5B3GOKmcSBNXh
 cZBdHZpROf2wT2Owost32TE=
X-Google-Smtp-Source: AMrXdXtEAUua9QvVMDldq/9/0BOQieLGZ8+WCULO5CR90IiI0G866rvhVJh2P9JyeB9rfoD17MoVfw==
X-Received: by 2002:a17:902:7584:b0:191:35c9:db30 with SMTP id
 j4-20020a170902758400b0019135c9db30mr19571753pll.5.1672090016975; 
 Mon, 26 Dec 2022 13:26:56 -0800 (PST)
Received: from smtpclient.apple (cpe-172-117-161-177.socal.res.rr.com.
 [172.117.161.177]) by smtp.gmail.com with ESMTPSA id
 l6-20020a170903120600b00190c6518e30sm7471478plh.243.2022.12.26.13.26.56
 (version=TLS1_2 cipher=ECDHE-ECDSA-AES128-GCM-SHA256 bits=128/128);
 Mon, 26 Dec 2022 13:26:56 -0800 (PST)
Content-Type: text/plain;
	charset=utf-8
Mime-Version: 1.0 (Mac OS X Mail 16.0 \(3696.120.41.1.1\))
Subject: Re: bug#60128: 30.0.50; [PATCH]: Add treesit-transpose-sexps
From: Yuan Fu <casouri@HIDDEN>
In-Reply-To: <873591honu.fsf@HIDDEN>
Date: Mon, 26 Dec 2022 13:26:54 -0800
Content-Transfer-Encoding: quoted-printable
Message-Id: <0D9F1198-B5FB-451D-B0E8-DB22910DAB58@HIDDEN>
References: <87a63nru7n.fsf@HIDDEN> <87edsytcoh.fsf@HIDDEN>
 <873591honu.fsf@HIDDEN>
To: Theodor Thornhill <theo@HIDDEN>
X-Mailer: Apple Mail (2.3696.120.41.1.1)
X-Spam-Score: 0.0 (/)
X-Debbugs-Envelope-To: 60128
Cc: 60128 <at> debbugs.gnu.org, eliz@HIDDEN,
 Stefan Monnier <monnier@HIDDEN>
X-BeenThere: debbugs-submit <at> debbugs.gnu.org
X-Mailman-Version: 2.1.18
Precedence: list
List-Id: <debbugs-submit.debbugs.gnu.org>
List-Unsubscribe: <https://debbugs.gnu.org/cgi-bin/mailman/options/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=unsubscribe>
List-Archive: <https://debbugs.gnu.org/cgi-bin/mailman/private/debbugs-submit/>
List-Post: <mailto:debbugs-submit <at> debbugs.gnu.org>
List-Help: <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=help>
List-Subscribe: <https://debbugs.gnu.org/cgi-bin/mailman/listinfo/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=subscribe>
Errors-To: debbugs-submit-bounces <at> debbugs.gnu.org
Sender: "Debbugs-submit" <debbugs-submit-bounces <at> debbugs.gnu.org>
X-Spam-Score: -1.0 (-)



> On Dec 26, 2022, at 12:53 PM, Theodor Thornhill <theo@HIDDEN> =
wrote:
>=20
> Theodor Thornhill <theo@HIDDEN> writes:
>=20
>> Theodor Thornhill <theo@HIDDEN> writes:
>>=20
>>> Hi there!
>>>=20
>>> Attached is a patch that enables transpose-sexps for tree-sitter =
enabled
>>> modes.
>>>=20
>>> This function will swap the node _before_ node-at-point with the =
node
>>> _after_, so it would do something like:
>>>=20
>>>       foo a|nd bar =3D> bar and foo|
>>>=20
>>> or
>>>       foo(a + 4,| y + c * b, b, d); =3D> foo(y + c * b, a + 4|, b, =
d);
>>>=20
>>> It will _not_ try to swap things that are not siblings.  I think =
that
>>> makes sense in the case of non-lisp languages, since _most_ places =
you
>>> can transpose-sexps you will end up with broken code.
>>>=20
>>=20
>> from 'transpose-subr-1':
>>=20
>>  (if (> (cdr pos1) (car pos2)) (error "Don't have two things to
>>  transpose"))
>>=20
>> I added this hack into the function in the patch, but I think that
>> triggering an error is too much.
>>=20
>>    ;; Hack to trigger the error message in `transpose-subr-1' when we
>>    ;; don't have siblings to swap.
>>    (list (cons 0 1) (cons 0 1))))
>>=20
>> I guess I could just follow suit in my function and do like in the
>> following patch:
>>=20
>> Theo
>=20
>=20
> Considering there is both a bug-report _and_ a discussion around this =
I
> guess the best idea is to add the patch to this bug report, and =
continue
> discussing this in the report rather than emacs-devel?
>=20
> What do you think about this patch?
>=20
> (copied from emacs-devel):
> It feels a little iffy how to handle the separate return values, but =
it
> works.  I'd be super happy for some feedback on how to best solve =
that,
> though :)

By separate return values, do you mean the function returns a cons of =
cons? It seems fine to me. Though I think the docstring could be more =
specific. Like saying return a cons (REGION . REGION), where REGION is =
(BEG . END), where BEG and END...

>=20
> Also, I made the treesit-transpose-sexps a little better imo, in that =
we
> only find named nodes to swap, but use every available node for the
> entry. We rarely, if ever want to swap the unnamed nodes.
>=20
> Eli, does this require a NEWS entry or more documentation?

IMHO a backend/helper function shouldn=E2=80=99t signal a user-error, =
it=E2=80=99s better to return nil and let the command to signal errors.

Yuan=




Information forwarded to bug-gnu-emacs@HIDDEN:
bug#60128; Package emacs. Full text available.

Message received at 60128 <at> debbugs.gnu.org:


Received: (at 60128) by debbugs.gnu.org; 26 Dec 2022 20:54:06 +0000
From debbugs-submit-bounces <at> debbugs.gnu.org Mon Dec 26 15:54:06 2022
Received: from localhost ([127.0.0.1]:54166 helo=debbugs.gnu.org)
	by debbugs.gnu.org with esmtp (Exim 4.84_2)
	(envelope-from <debbugs-submit-bounces <at> debbugs.gnu.org>)
	id 1p9uU1-0001mw-Ci
	for submit <at> debbugs.gnu.org; Mon, 26 Dec 2022 15:54:06 -0500
Received: from out-146.mta0.migadu.com ([91.218.175.146]:56349)
 by debbugs.gnu.org with esmtp (Exim 4.84_2)
 (envelope-from <theo@HIDDEN>) id 1p9uTx-0001mN-HY
 for 60128 <at> debbugs.gnu.org; Mon, 26 Dec 2022 15:54:04 -0500
X-Report-Abuse: Please report any abuse attempt to abuse@HIDDEN and
 include these headers.
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=thornhill.no;
 s=key1; t=1672088038;
 h=from:from:reply-to:subject:subject:date:date:message-id:message-id:
 to:to:cc:cc:mime-version:mime-version:content-type:content-type:
 in-reply-to:in-reply-to:references:references;
 bh=jHa3LtlgKnQd2q2wzTJgEnCBfRWNMC5P2w0f3mfkPPQ=;
 b=BkAbaYNQ325MijswxZQCY9NwZOI8wLRrOTiqJsB7oB9zAd0SK7Mo0354pMrqr2H8hpz8R6
 WUOtjsxkf6xtfVBxEcKG/dpF2asKlnngBrXuCHWK5Ka8+564wl3UmKvrisgrJNaD24YABA
 wibZVbnpLTJ8QfBaEoAL5heslog0/BS9QeeYD86WyYD9dO56+pMv1TeK4ZS2bf1bja1cgJ
 1OrP2L2RgLWYBoYY0/Reww+hXFZxY1MIGyyqpS9CqNXrJA/YTodfiGgqVrzFuPuAUvkP9J
 k6F6cWeLiDw2iqGF+hXI6GTfYJzYmVqZCLfdyBDzgN4tXW8fQPdqI/PEUbnQtA==
From: Theodor Thornhill <theo@HIDDEN>
To: 60128 <at> debbugs.gnu.org
Subject: Re: bug#60128: 30.0.50; [PATCH]: Add treesit-transpose-sexps
In-Reply-To: <87edsytcoh.fsf@HIDDEN> (Theodor Thornhill's message of
 "Sat, 17 Dec 2022 13:52:30 +0100")
References: <87a63nru7n.fsf@HIDDEN> <87edsytcoh.fsf@HIDDEN>
Date: Mon, 26 Dec 2022 21:53:57 +0100
Message-ID: <873591honu.fsf@HIDDEN>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="=-=-="
X-Migadu-Flow: FLOW_OUT
X-Spam-Score: 0.0 (/)
X-Debbugs-Envelope-To: 60128
Cc: casouri@HIDDEN, eliz@HIDDEN, Stefan Monnier <monnier@HIDDEN>
X-BeenThere: debbugs-submit <at> debbugs.gnu.org
X-Mailman-Version: 2.1.18
Precedence: list
List-Id: <debbugs-submit.debbugs.gnu.org>
List-Unsubscribe: <https://debbugs.gnu.org/cgi-bin/mailman/options/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=unsubscribe>
List-Archive: <https://debbugs.gnu.org/cgi-bin/mailman/private/debbugs-submit/>
List-Post: <mailto:debbugs-submit <at> debbugs.gnu.org>
List-Help: <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=help>
List-Subscribe: <https://debbugs.gnu.org/cgi-bin/mailman/listinfo/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=subscribe>
Errors-To: debbugs-submit-bounces <at> debbugs.gnu.org
Sender: "Debbugs-submit" <debbugs-submit-bounces <at> debbugs.gnu.org>
X-Spam-Score: -1.0 (-)

--=-=-=
Content-Type: text/plain

Theodor Thornhill <theo@HIDDEN> writes:

> Theodor Thornhill <theo@HIDDEN> writes:
>
>> Hi there!
>>
>> Attached is a patch that enables transpose-sexps for tree-sitter enabled
>> modes.
>>
>> This function will swap the node _before_ node-at-point with the node
>> _after_, so it would do something like:
>>
>>        foo a|nd bar => bar and foo|
>>
>> or
>>        foo(a + 4,| y + c * b, b, d); => foo(y + c * b, a + 4|, b, d);
>>
>> It will _not_ try to swap things that are not siblings.  I think that
>> makes sense in the case of non-lisp languages, since _most_ places you
>> can transpose-sexps you will end up with broken code.
>>
>
> from 'transpose-subr-1':
>
>   (if (> (cdr pos1) (car pos2)) (error "Don't have two things to
>   transpose"))
>
> I added this hack into the function in the patch, but I think that
> triggering an error is too much.
>
>     ;; Hack to trigger the error message in `transpose-subr-1' when we
>     ;; don't have siblings to swap.
>     (list (cons 0 1) (cons 0 1))))
>
> I guess I could just follow suit in my function and do like in the
> following patch:
>
> Theo


Considering there is both a bug-report _and_ a discussion around this I
guess the best idea is to add the patch to this bug report, and continue
discussing this in the report rather than emacs-devel?

What do you think about this patch?

(copied from emacs-devel):
It feels a little iffy how to handle the separate return values, but it
works.  I'd be super happy for some feedback on how to best solve that,
though :)

Also, I made the treesit-transpose-sexps a little better imo, in that we
only find named nodes to swap, but use every available node for the
entry. We rarely, if ever want to swap the unnamed nodes.

Eli, does this require a NEWS entry or more documentation?

Theo


--=-=-=
Content-Type: text/x-diff
Content-Disposition: attachment;
 filename=0001-Add-treesit-transpose-sexps-bug-60128.patch

From 0dc412eaf16123dcb65381970fb82c0741809753 Mon Sep 17 00:00:00 2001
From: Theodor Thornhill <theo@HIDDEN>
Date: Sun, 25 Dec 2022 20:11:59 +0100
Subject: [PATCH] Add treesit-transpose-sexps (bug#60128)

We don't really need to rely on forward-sexp to define what to
transpose.  In tree-sitter we can consider siblings as "balanced
expressions", and swap them without doing any movement to calculate
where the siblings in question are.

* lisp/simple.el (transpose-sexps-function): New defvar-local.
(transpose-sexps): Use the new defvar-local if available.
(transpose-subr): Check whether the mover function returns a cons of
conses, then run transpose-subr-1 on the position-pairs.
* lisp/treesit.el (treesit-transpose-sexps): New function.
---
 lisp/simple.el  | 97 ++++++++++++++++++++++++++++---------------------
 lisp/treesit.el | 24 +++++++++++-
 2 files changed, 78 insertions(+), 43 deletions(-)

diff --git a/lisp/simple.el b/lisp/simple.el
index 4551b749d5..591b659c62 100644
--- a/lisp/simple.el
+++ b/lisp/simple.el
@@ -8438,6 +8438,14 @@ transpose-words
   (interactive "*p")
   (transpose-subr 'forward-word arg))
 
+(defvar-local transpose-sexps-function nil
+  "If non-nil, `transpose-sexps' delegates to this function.
+
+The return value of this function is expected to be a cons of two
+conses, denoting the positions in the current buffer to be
+transposed.  If no such pair of positions is available, signal
+USER-ERROR.")
+
 (defun transpose-sexps (arg &optional interactive)
   "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
 Unlike `transpose-words', point must be between the two sexps and not
@@ -8454,36 +8462,37 @@ transpose-sexps
           (transpose-sexps arg nil)
         (scan-error (user-error "Not between two complete sexps")))
     (transpose-subr
-     (lambda (arg)
-       ;; Here we should try to simulate the behavior of
-       ;; (cons (progn (forward-sexp x) (point))
-       ;;       (progn (forward-sexp (- x)) (point)))
-       ;; Except that we don't want to rely on the second forward-sexp
-       ;; putting us back to where we want to be, since forward-sexp-function
-       ;; might do funny things like infix-precedence.
-       (if (if (> arg 0)
-	       (looking-at "\\sw\\|\\s_")
-	     (and (not (bobp))
-		  (save-excursion
-                    (forward-char -1)
-                    (looking-at "\\sw\\|\\s_"))))
-	   ;; Jumping over a symbol.  We might be inside it, mind you.
-	   (progn (funcall (if (> arg 0)
-			       'skip-syntax-backward 'skip-syntax-forward)
-			   "w_")
-		  (cons (save-excursion (forward-sexp arg) (point)) (point)))
-         ;; Otherwise, we're between sexps.  Take a step back before jumping
-         ;; to make sure we'll obey the same precedence no matter which
-         ;; direction we're going.
-         (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward)
-                  " .")
-         (cons (save-excursion (forward-sexp arg) (point))
-	       (progn (while (or (forward-comment (if (> arg 0) 1 -1))
-			         (not (zerop (funcall (if (> arg 0)
-							  'skip-syntax-forward
-						        'skip-syntax-backward)
-						      ".")))))
-		      (point)))))
+     (if transpose-sexps-function transpose-sexps-function
+       (lambda (arg)
+         ;; Here we should try to simulate the behavior of
+         ;; (cons (progn (forward-sexp x) (point))
+         ;;       (progn (forward-sexp (- x)) (point)))
+         ;; Except that we don't want to rely on the second forward-sexp
+         ;; putting us back to where we want to be, since forward-sexp-function
+         ;; might do funny things like infix-precedence.
+         (if (if (> arg 0)
+	         (looking-at "\\sw\\|\\s_")
+	       (and (not (bobp))
+	            (save-excursion
+                      (forward-char -1)
+                      (looking-at "\\sw\\|\\s_"))))
+             ;; Jumping over a symbol.  We might be inside it, mind you.
+	     (progn (funcall (if (> arg 0)
+			         #'skip-syntax-backward #'skip-syntax-forward)
+			     "w_")
+	            (cons (save-excursion (forward-sexp arg) (point)) (point)))
+           ;; Otherwise, we're between sexps.  Take a step back before jumping
+           ;; to make sure we'll obey the same precedence no matter which
+           ;; direction we're going.
+           (funcall (if (> arg 0) #'skip-syntax-backward #'skip-syntax-forward)
+                    " .")
+           (cons (save-excursion (forward-sexp arg) (point))
+	         (progn (while (or (forward-comment (if (> arg 0) 1 -1))
+			           (not (zerop (funcall (if (> arg 0)
+						            #'skip-syntax-forward
+						          #'skip-syntax-backward)
+						        ".")))))
+		        (point))))))
      arg 'special)))
 
 (defun transpose-lines (arg)
@@ -8509,19 +8518,23 @@ transpose-lines
 ;; FIXME document SPECIAL.
 (defun transpose-subr (mover arg &optional special)
   "Subroutine to do the work of transposing objects.
-Works for lines, sentences, paragraphs, etc.  MOVER is a function that
-moves forward by units of the given object (e.g. `forward-sentence',
-`forward-paragraph').  If ARG is zero, exchanges the current object
-with the one containing mark.  If ARG is an integer, moves the
-current object past ARG following (if ARG is positive) or
-preceding (if ARG is negative) objects, leaving point after the
-current object."
-  (let ((aux (if special mover
-	       (lambda (x)
-		 (cons (progn (funcall mover x) (point))
-		       (progn (funcall mover (- x)) (point))))))
-	pos1 pos2)
+Works for lines, sentences, paragraphs, etc.  MOVER is either a
+function that moves forward by units of the given
+object (e.g. `forward-sentence', `forward-paragraph'), or a
+function that calculates a cons of two position-pairs.  If ARG is
+zero, exchanges the current object with the one containing mark.
+If ARG is an integer, moves the current object past ARG
+following (if ARG is positive) or preceding (if ARG is negative)
+objects, leaving point after the current object."
+  (let* ((aux (if special mover
+	        (lambda (x)
+		  (cons (progn (funcall mover x) (point))
+		        (progn (funcall mover (- x)) (point))))))
+	 (pos1 (save-excursion (funcall aux arg)))
+         pos2)
     (cond
+     ((and (consp (car pos1)) (consp (cdr pos1)))
+      (transpose-subr-1 (car pos1) (cdr pos1)))
      ((= arg 0)
       (save-excursion
 	(setq pos1 (funcall aux 1))
diff --git a/lisp/treesit.el b/lisp/treesit.el
index cefbed1a16..9f0965ac68 100644
--- a/lisp/treesit.el
+++ b/lisp/treesit.el
@@ -1582,6 +1582,27 @@ treesit-search-forward-goto
       (goto-char current-pos)))
     node))
 
+(defun treesit-transpose-sexps (&optional arg)
+  "Tree-sitter `transpose-sexps' function.
+Arg is the same as in `transpose-sexps'.
+
+Return a pair of positions describing the regions to transpose
+for use in `transpose-subr' and friends."
+  (let* ((parent (treesit-node-parent (treesit-node-at (point))))
+         (child (treesit-node-child parent 0 t)))
+    (named-let loop ((prev child)
+                     (next (treesit-node-child
+                            parent (+ arg (treesit-node-index child t))
+                            t)))
+      (if (< (point) (or (treesit-node-end next)
+                         (user-error "Don't have two things to transpose")))
+          (cons (cons (treesit-node-start prev)
+                      (treesit-node-end prev))
+                (cons (treesit-node-start next)
+                      (treesit-node-end next)))
+        (loop (treesit-node-next-sibling prev t)
+              (treesit-node-next-sibling next t))))))
+
 ;;; Navigation, defun, things
 ;;
 ;; Emacs lets you define "things" by a regexp that matches the type of
@@ -2111,7 +2132,8 @@ treesit-major-mode-setup
   ;; Defun name.
   (when treesit-defun-name-function
     (setq-local add-log-current-defun-function
-                #'treesit-add-log-current-defun)))
+                #'treesit-add-log-current-defun))
+  (setq-local transpose-sexps-function #'treesit-transpose-sexps))
 
 ;;; Debugging
 
-- 
2.34.1


--=-=-=--




Information forwarded to bug-gnu-emacs@HIDDEN:
bug#60128; Package emacs. Full text available.

Message received at 60128 <at> debbugs.gnu.org:


Received: (at 60128) by debbugs.gnu.org; 17 Dec 2022 12:52:36 +0000
From debbugs-submit-bounces <at> debbugs.gnu.org Sat Dec 17 07:52:36 2022
Received: from localhost ([127.0.0.1]:55783 helo=debbugs.gnu.org)
	by debbugs.gnu.org with esmtp (Exim 4.84_2)
	(envelope-from <debbugs-submit-bounces <at> debbugs.gnu.org>)
	id 1p6Wg8-0000Xu-2c
	for submit <at> debbugs.gnu.org; Sat, 17 Dec 2022 07:52:36 -0500
Received: from out-193.mta0.migadu.com ([91.218.175.193]:57525)
 by debbugs.gnu.org with esmtp (Exim 4.84_2)
 (envelope-from <theo@HIDDEN>) id 1p6Wg5-0000Xd-4t
 for 60128 <at> debbugs.gnu.org; Sat, 17 Dec 2022 07:52:34 -0500
X-Report-Abuse: Please report any abuse attempt to abuse@HIDDEN and
 include these headers.
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=thornhill.no;
 s=key1; t=1671281551;
 h=from:from:reply-to:subject:subject:date:date:message-id:message-id:
 to:to:cc:cc:mime-version:mime-version:content-type:content-type:
 in-reply-to:in-reply-to:references:references;
 bh=Trvgd0nvj7ZQO0bO7jYjGO1cB41Mdw9080M3qyXstTs=;
 b=H4PwfK+BrpEg6UXA2eaaC8H/hG6PF23gp6uc7zPcQdgecRDFal3TPPGbFvkyNhelpLAIdb
 /BzM+bKV3QERMhsQzUVgPAK5GBJoba1CNXRKQSr1ENgag5wSvM9aphllmT8aMvmFXQ9bl8
 92Bqw52TaoQIJSWJ86vpVjcoEFrIu62vupB9hQb3m87EkM0masob/hqLKy0Idc1y9HQdlf
 TfTr8acDcmHjIO15IlGI076TKf9VUdFZatK61u78NXyVDXDJ/NwoGkjDCCbujrlBuinGJW
 aAhWUTIDwxSqIVv8Is99DkWyg2gj22B6cszsHIdeL8hbroduNZsleSpyzhMv6g==
From: Theodor Thornhill <theo@HIDDEN>
To: 60128 <at> debbugs.gnu.org
Subject: Re: bug#60128: 30.0.50; [PATCH]: Add treesit-transpose-sexps
In-Reply-To: <87a63nru7n.fsf@HIDDEN> (Theodor Thornhill's message of
 "Fri, 16 Dec 2022 21:04:28 +0100")
References: <87a63nru7n.fsf@HIDDEN>
Date: Sat, 17 Dec 2022 13:52:30 +0100
Message-ID: <87edsytcoh.fsf@HIDDEN>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="=-=-="
X-Migadu-Flow: FLOW_OUT
X-Spam-Score: 0.0 (/)
X-Debbugs-Envelope-To: 60128
Cc: casouri@HIDDEN, Stefan Monnier <monnier@HIDDEN>
X-BeenThere: debbugs-submit <at> debbugs.gnu.org
X-Mailman-Version: 2.1.18
Precedence: list
List-Id: <debbugs-submit.debbugs.gnu.org>
List-Unsubscribe: <https://debbugs.gnu.org/cgi-bin/mailman/options/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=unsubscribe>
List-Archive: <https://debbugs.gnu.org/cgi-bin/mailman/private/debbugs-submit/>
List-Post: <mailto:debbugs-submit <at> debbugs.gnu.org>
List-Help: <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=help>
List-Subscribe: <https://debbugs.gnu.org/cgi-bin/mailman/listinfo/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=subscribe>
Errors-To: debbugs-submit-bounces <at> debbugs.gnu.org
Sender: "Debbugs-submit" <debbugs-submit-bounces <at> debbugs.gnu.org>
X-Spam-Score: -1.0 (-)

--=-=-=
Content-Type: text/plain

Theodor Thornhill <theo@HIDDEN> writes:

> Hi there!
>
> Attached is a patch that enables transpose-sexps for tree-sitter enabled
> modes.
>
> This function will swap the node _before_ node-at-point with the node
> _after_, so it would do something like:
>
>        foo a|nd bar => bar and foo|
>
> or
>        foo(a + 4,| y + c * b, b, d); => foo(y + c * b, a + 4|, b, d);
>
> It will _not_ try to swap things that are not siblings.  I think that
> makes sense in the case of non-lisp languages, since _most_ places you
> can transpose-sexps you will end up with broken code.
>

from 'transpose-subr-1':

  (if (> (cdr pos1) (car pos2)) (error "Don't have two things to
  transpose"))

I added this hack into the function in the patch, but I think that
triggering an error is too much.

    ;; Hack to trigger the error message in `transpose-subr-1' when we
    ;; don't have siblings to swap.
    (list (cons 0 1) (cons 0 1))))

I guess I could just follow suit in my function and do like in the
following patch:

Theo


--=-=-=
Content-Type: text/x-diff
Content-Disposition: attachment;
 filename=0001-Add-treesit-transpose-sexps.patch

From e26dc6ab62ddf7b60fcbe2532acdf9f8500c904f Mon Sep 17 00:00:00 2001
From: Theodor Thornhill <theo@HIDDEN>
Date: Thu, 15 Dec 2022 21:22:13 +0100
Subject: [PATCH] Add treesit-transpose-sexps

We don't really need to rely on forward-sexp to define what to
transpose.  In tree-sitter we can consider siblings as "balanced
expressions", and swap them without doing any movement to calculate
where the siblings in question are.

* lisp/simple.el: Add requires for treesit.
* lisp/simple.el (transpose-sexps): If tree-sitter is available, use
treesit-transpose-sexps as the 'special' function.
(transpose-subr): Just use tree-sitter when available.
* lisp/treesit.el (treesit-transpose-sexps): New function.
---
 lisp/simple.el  | 67 ++++++++++++++++++++++++++-----------------------
 lisp/treesit.el | 14 +++++++++++
 2 files changed, 50 insertions(+), 31 deletions(-)

diff --git a/lisp/simple.el b/lisp/simple.el
index dcc2242e49..15f7381f06 100644
--- a/lisp/simple.el
+++ b/lisp/simple.el
@@ -28,10 +28,12 @@
 
 ;;; Code:
 
-(eval-when-compile (require 'cl-lib))
+(eval-when-compile (require 'cl-lib)
+                   (require 'treesit))
 
 (declare-function widget-convert "wid-edit" (type &rest args))
 (declare-function shell-mode "shell" ())
+(declare-function treesit-parser-list "treesit.c")
 
 ;;; From compile.el
 (defvar compilation-current-error)
@@ -8453,36 +8455,37 @@ transpose-sexps
           (transpose-sexps arg nil)
         (scan-error (user-error "Not between two complete sexps")))
     (transpose-subr
-     (lambda (arg)
-       ;; Here we should try to simulate the behavior of
-       ;; (cons (progn (forward-sexp x) (point))
-       ;;       (progn (forward-sexp (- x)) (point)))
-       ;; Except that we don't want to rely on the second forward-sexp
-       ;; putting us back to where we want to be, since forward-sexp-function
-       ;; might do funny things like infix-precedence.
-       (if (if (> arg 0)
-	       (looking-at "\\sw\\|\\s_")
-	     (and (not (bobp))
-		  (save-excursion
-                    (forward-char -1)
-                    (looking-at "\\sw\\|\\s_"))))
-	   ;; Jumping over a symbol.  We might be inside it, mind you.
-	   (progn (funcall (if (> arg 0)
-			       'skip-syntax-backward 'skip-syntax-forward)
-			   "w_")
-		  (cons (save-excursion (forward-sexp arg) (point)) (point)))
-         ;; Otherwise, we're between sexps.  Take a step back before jumping
-         ;; to make sure we'll obey the same precedence no matter which
-         ;; direction we're going.
-         (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward)
-                  " .")
-         (cons (save-excursion (forward-sexp arg) (point))
-	       (progn (while (or (forward-comment (if (> arg 0) 1 -1))
-			         (not (zerop (funcall (if (> arg 0)
-							  'skip-syntax-forward
-						        'skip-syntax-backward)
-						      ".")))))
-		      (point)))))
+     (if (treesit-parser-list) #'treesit-transpose-sexps
+       (lambda (arg)
+         ;; Here we should try to simulate the behavior of
+         ;; (cons (progn (forward-sexp x) (point))
+         ;;       (progn (forward-sexp (- x)) (point)))
+         ;; Except that we don't want to rely on the second forward-sexp
+         ;; putting us back to where we want to be, since forward-sexp-function
+         ;; might do funny things like infix-precedence.
+         (if (if (> arg 0)
+	         (looking-at "\\sw\\|\\s_")
+	       (and (not (bobp))
+		    (save-excursion
+                      (forward-char -1)
+                      (looking-at "\\sw\\|\\s_"))))
+             ;; Jumping over a symbol.  We might be inside it, mind you.
+	     (progn (funcall (if (> arg 0)
+			         'skip-syntax-backward 'skip-syntax-forward)
+			     "w_")
+		    (cons (save-excursion (forward-sexp arg) (point)) (point)))
+           ;; Otherwise, we're between sexps.  Take a step back before jumping
+           ;; to make sure we'll obey the same precedence no matter which
+           ;; direction we're going.
+           (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward)
+                    " .")
+           (cons (save-excursion (forward-sexp arg) (point))
+	         (progn (while (or (forward-comment (if (> arg 0) 1 -1))
+			           (not (zerop (funcall (if (> arg 0)
+							    'skip-syntax-forward
+						          'skip-syntax-backward)
+						        ".")))))
+		        (point))))))
      arg 'special)))
 
 (defun transpose-lines (arg)
@@ -8521,6 +8524,8 @@ transpose-subr
 		       (progn (funcall mover (- x)) (point))))))
 	pos1 pos2)
     (cond
+     ((treesit-parser-list)
+      (apply #'transpose-subr-1 (funcall aux arg)))
      ((= arg 0)
       (save-excursion
 	(setq pos1 (funcall aux 1))
diff --git a/lisp/treesit.el b/lisp/treesit.el
index 0df71d12ed..1504ad3482 100644
--- a/lisp/treesit.el
+++ b/lisp/treesit.el
@@ -1623,6 +1623,20 @@ treesit--defun-maybe-top-level
                  node)
       finally return node))))
 
+(defun treesit-transpose-sexps (&optional arg)
+  "Tree-sitter `transpose-sexps' function.
+Arg is the same as in `transpose-sexps'."
+  (if-let* ((node (treesit-node-at (point)))
+            (parent (treesit-node-parent node))
+            (index (treesit-node-index node))
+            (prev (treesit-node-child parent (1- index)))
+            (next (treesit-node-child parent (+ arg index))))
+      (list (cons (treesit-node-start prev)
+                  (treesit-node-end prev))
+            (cons (treesit-node-start next)
+                  (treesit-node-end next)))
+    (user-error "Don't have two things to transpose")))
+
 (defun treesit-beginning-of-defun (&optional arg)
   "Move backward to the beginning of a defun.
 
-- 
2.34.1


--=-=-=--




Information forwarded to bug-gnu-emacs@HIDDEN:
bug#60128; Package emacs. Full text available.

Message received at submit <at> debbugs.gnu.org:


Received: (at submit) by debbugs.gnu.org; 16 Dec 2022 20:04:57 +0000
From debbugs-submit-bounces <at> debbugs.gnu.org Fri Dec 16 15:04:57 2022
Received: from localhost ([127.0.0.1]:51301 helo=debbugs.gnu.org)
	by debbugs.gnu.org with esmtp (Exim 4.84_2)
	(envelope-from <debbugs-submit-bounces <at> debbugs.gnu.org>)
	id 1p6Gwz-0006Cu-3w
	for submit <at> debbugs.gnu.org; Fri, 16 Dec 2022 15:04:57 -0500
Received: from lists.gnu.org ([209.51.188.17]:48416)
 by debbugs.gnu.org with esmtp (Exim 4.84_2)
 (envelope-from <theo@HIDDEN>) id 1p6Gwx-0006Cm-Ff
 for submit <at> debbugs.gnu.org; Fri, 16 Dec 2022 15:04:56 -0500
Received: from eggs.gnu.org ([2001:470:142:3::10])
 by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256)
 (Exim 4.90_1) (envelope-from <theo@HIDDEN>) id 1p6Gwj-0006Ja-Km
 for bug-gnu-emacs@HIDDEN; Fri, 16 Dec 2022 15:04:51 -0500
Received: from out2.migadu.com ([2001:41d0:2:aacc::])
 by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256)
 (Exim 4.90_1) (envelope-from <theo@HIDDEN>) id 1p6Gwf-0002PV-B6
 for bug-gnu-emacs@HIDDEN; Fri, 16 Dec 2022 15:04:39 -0500
X-Report-Abuse: Please report any abuse attempt to abuse@HIDDEN and
 include these headers.
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=thornhill.no;
 s=key1; t=1671221070;
 h=from:from:reply-to:subject:subject:date:date:message-id:message-id:
 to:to:cc:mime-version:mime-version:content-type:content-type;
 bh=nTkYw7zr4gD7A0I/udfBGN9G28I6Cpo7FxzKGWHn8h4=;
 b=A0D77jflpOjm/uKQ/rvO40Tc/cfe+VDFnhPOz9M2RduLIm7pNRr7Gdvy2byHyIKikfFxHe
 +2g0toAlx0w8izz01WxHUELF1s1QGNs9ryYvGN8IK3J5uF+6AWIriGNgYib1oT4039110l
 7Du/KXCl82LRds9xCvqFmyXPfuSBOUnnATm76rYRWy80lST9gJd/F0Vq2gkNyKNLkQ2V34
 mjjOuTnMLdTGEJZ+iqI41S5BNC7IGzl4MRhrpz9nfXhkvVwDTld/Gcpgz5q4HAt5b5pmHp
 +RwOxDPb4vmNFuNReNljbyfS6KKsP/n2kFIxB/NSjltGXsHDalVHXxcX3zO74A==
From: Theodor Thornhill <theo@HIDDEN>
To: bug-gnu-emacs@HIDDEN
Subject: 30.0.50; [PATCH]: Add treesit-transpose-sexps
X-Debbugs-Cc: casouri@HIDDEN, Stefan Monnier <monnier@HIDDEN>
Date: Fri, 16 Dec 2022 21:04:28 +0100
Message-ID: <87a63nru7n.fsf@HIDDEN>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="=-=-="
X-Migadu-Flow: FLOW_OUT
Received-SPF: pass client-ip=2001:41d0:2:aacc::;
 envelope-from=theo@HIDDEN; helo=out2.migadu.com
X-Spam_score_int: -27
X-Spam_score: -2.8
X-Spam_bar: --
X-Spam_report: (-2.8 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1,
 DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1,
 RCVD_IN_DNSWL_LOW=-0.7, SPF_HELO_PASS=-0.001,
 SPF_PASS=-0.001 autolearn=ham autolearn_force=no
X-Spam_action: no action
X-Spam-Score: -1.4 (-)
X-Debbugs-Envelope-To: submit
X-BeenThere: debbugs-submit <at> debbugs.gnu.org
X-Mailman-Version: 2.1.18
Precedence: list
List-Id: <debbugs-submit.debbugs.gnu.org>
List-Unsubscribe: <https://debbugs.gnu.org/cgi-bin/mailman/options/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=unsubscribe>
List-Archive: <https://debbugs.gnu.org/cgi-bin/mailman/private/debbugs-submit/>
List-Post: <mailto:debbugs-submit <at> debbugs.gnu.org>
List-Help: <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=help>
List-Subscribe: <https://debbugs.gnu.org/cgi-bin/mailman/listinfo/debbugs-submit>, 
 <mailto:debbugs-submit-request <at> debbugs.gnu.org?subject=subscribe>
Errors-To: debbugs-submit-bounces <at> debbugs.gnu.org
Sender: "Debbugs-submit" <debbugs-submit-bounces <at> debbugs.gnu.org>
X-Spam-Score: -2.4 (--)

--=-=-=
Content-Type: text/plain


Hi there!

Attached is a patch that enables transpose-sexps for tree-sitter enabled
modes.

This function will swap the node _before_ node-at-point with the node
_after_, so it would do something like:

       foo a|nd bar => bar and foo|

or
       foo(a + 4,| y + c * b, b, d); => foo(y + c * b, a + 4|, b, d);

It will _not_ try to swap things that are not siblings.  I think that
makes sense in the case of non-lisp languages, since _most_ places you
can transpose-sexps you will end up with broken code.

What do you think?  I think this makes sense on the master branch, not
release.

Theo


--=-=-=
Content-Type: text/x-diff
Content-Disposition: attachment;
 filename=0001-Add-treesit-transpose-sexps.patch

From 9c2bf9869fbd76b81c21f13a02d70e85eec736be Mon Sep 17 00:00:00 2001
From: Theodor Thornhill <theo@HIDDEN>
Date: Thu, 15 Dec 2022 21:22:13 +0100
Subject: [PATCH] Add treesit-transpose-sexps

We don't really need to rely on forward-sexp to define what to
transpose.  In tree-sitter we can consider siblings as "balanced
expressions", and swap them without doing any movement to calculate
where the siblings in question are.

* lisp/simple.el: Add requires for treesit.
* lisp/simple.el (transpose-sexps): If tree-sitter is available, use
treesit-transpose-sexps as the 'special' function.
(transpose-subr): Just use tree-sitter when available.
* lisp/treesit.el (treesit-transpose-sexps): New function.
---
 lisp/simple.el  | 67 ++++++++++++++++++++++++++-----------------------
 lisp/treesit.el | 16 ++++++++++++
 2 files changed, 52 insertions(+), 31 deletions(-)

diff --git a/lisp/simple.el b/lisp/simple.el
index dcc2242e49..15f7381f06 100644
--- a/lisp/simple.el
+++ b/lisp/simple.el
@@ -28,10 +28,12 @@
 
 ;;; Code:
 
-(eval-when-compile (require 'cl-lib))
+(eval-when-compile (require 'cl-lib)
+                   (require 'treesit))
 
 (declare-function widget-convert "wid-edit" (type &rest args))
 (declare-function shell-mode "shell" ())
+(declare-function treesit-parser-list "treesit.c")
 
 ;;; From compile.el
 (defvar compilation-current-error)
@@ -8453,36 +8455,37 @@ transpose-sexps
           (transpose-sexps arg nil)
         (scan-error (user-error "Not between two complete sexps")))
     (transpose-subr
-     (lambda (arg)
-       ;; Here we should try to simulate the behavior of
-       ;; (cons (progn (forward-sexp x) (point))
-       ;;       (progn (forward-sexp (- x)) (point)))
-       ;; Except that we don't want to rely on the second forward-sexp
-       ;; putting us back to where we want to be, since forward-sexp-function
-       ;; might do funny things like infix-precedence.
-       (if (if (> arg 0)
-	       (looking-at "\\sw\\|\\s_")
-	     (and (not (bobp))
-		  (save-excursion
-                    (forward-char -1)
-                    (looking-at "\\sw\\|\\s_"))))
-	   ;; Jumping over a symbol.  We might be inside it, mind you.
-	   (progn (funcall (if (> arg 0)
-			       'skip-syntax-backward 'skip-syntax-forward)
-			   "w_")
-		  (cons (save-excursion (forward-sexp arg) (point)) (point)))
-         ;; Otherwise, we're between sexps.  Take a step back before jumping
-         ;; to make sure we'll obey the same precedence no matter which
-         ;; direction we're going.
-         (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward)
-                  " .")
-         (cons (save-excursion (forward-sexp arg) (point))
-	       (progn (while (or (forward-comment (if (> arg 0) 1 -1))
-			         (not (zerop (funcall (if (> arg 0)
-							  'skip-syntax-forward
-						        'skip-syntax-backward)
-						      ".")))))
-		      (point)))))
+     (if (treesit-parser-list) #'treesit-transpose-sexps
+       (lambda (arg)
+         ;; Here we should try to simulate the behavior of
+         ;; (cons (progn (forward-sexp x) (point))
+         ;;       (progn (forward-sexp (- x)) (point)))
+         ;; Except that we don't want to rely on the second forward-sexp
+         ;; putting us back to where we want to be, since forward-sexp-function
+         ;; might do funny things like infix-precedence.
+         (if (if (> arg 0)
+	         (looking-at "\\sw\\|\\s_")
+	       (and (not (bobp))
+		    (save-excursion
+                      (forward-char -1)
+                      (looking-at "\\sw\\|\\s_"))))
+             ;; Jumping over a symbol.  We might be inside it, mind you.
+	     (progn (funcall (if (> arg 0)
+			         'skip-syntax-backward 'skip-syntax-forward)
+			     "w_")
+		    (cons (save-excursion (forward-sexp arg) (point)) (point)))
+           ;; Otherwise, we're between sexps.  Take a step back before jumping
+           ;; to make sure we'll obey the same precedence no matter which
+           ;; direction we're going.
+           (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward)
+                    " .")
+           (cons (save-excursion (forward-sexp arg) (point))
+	         (progn (while (or (forward-comment (if (> arg 0) 1 -1))
+			           (not (zerop (funcall (if (> arg 0)
+							    'skip-syntax-forward
+						          'skip-syntax-backward)
+						        ".")))))
+		        (point))))))
      arg 'special)))
 
 (defun transpose-lines (arg)
@@ -8521,6 +8524,8 @@ transpose-subr
 		       (progn (funcall mover (- x)) (point))))))
 	pos1 pos2)
     (cond
+     ((treesit-parser-list)
+      (apply #'transpose-subr-1 (funcall aux arg)))
      ((= arg 0)
       (save-excursion
 	(setq pos1 (funcall aux 1))
diff --git a/lisp/treesit.el b/lisp/treesit.el
index 0df71d12ed..69b53bde5d 100644
--- a/lisp/treesit.el
+++ b/lisp/treesit.el
@@ -1623,6 +1623,22 @@ treesit--defun-maybe-top-level
                  node)
       finally return node))))
 
+(defun treesit-transpose-sexps (&optional arg)
+  "Tree-sitter `transpose-sexps' function.
+Arg is the same as in `transpose-sexps'."
+  (interactive "*p")
+  (if-let* ((node (treesit-node-at (point)))
+            (parent (treesit-node-parent node))
+            (index (treesit-node-index node))
+            (prev (treesit-node-child parent (1- index)))
+            (next (treesit-node-child parent (+ arg index))))
+      (list (cons (treesit-node-start prev)
+                  (treesit-node-end prev))
+            (cons (treesit-node-start next)
+                  (treesit-node-end next)))
+    ;; Hack to trigger the error message in `transpose-subr-1' when we
+    ;; don't have siblings to swap.
+    (list (cons 0 1) (cons 0 1))))
 (defun treesit-beginning-of-defun (&optional arg)
   "Move backward to the beginning of a defun.
 
-- 
2.34.1


--=-=-=--




Acknowledgement sent to Theodor Thornhill <theo@HIDDEN>:
New bug report received and forwarded. Copy sent to casouri@HIDDEN, monnier@HIDDEN, bug-gnu-emacs@HIDDEN. Full text available.
Report forwarded to casouri@HIDDEN, monnier@HIDDEN, bug-gnu-emacs@HIDDEN:
bug#60128; Package emacs. Full text available.
Please note: This is a static page, with minimal formatting, updated once a day.
Click here to see this page with the latest information and nicer formatting.
Last modified: Sat, 7 Jan 2023 23:30:02 UTC

GNU bug tracking system
Copyright (C) 1999 Darren O. Benham, 1997 nCipher Corporation Ltd, 1994-97 Ian Jackson.